How to use the Hyperf framework for JWT authentication
Introduction:
Hyperf is a high-performance coroutine framework based on Swoole, providing rich functions and flexibility scalability. JWT (JSON Web Token) is an open standard for authenticating and transmitting information. In this article, we will introduce how to use JWT authentication in the Hyperf framework and provide specific code examples.
1. Install dependency packages
First, we need to install hyperf/jwt and lcobucci/jwt dependency packages. It can be installed through Composer, open the terminal and run the following command:
composer require hyperf/jwt lcobucci/jwt
2. Configure authentication information
In the Hyperf framework, we need to configure the relevant information required for JWT authentication. Open the config/autoload/jwt.php
file and add the following configuration items:
<?php return [ 'default' => [ 'valid_seconds' => env('JWT_VALID_SECONDS', 3600), // Token有效期 'secret' => env('JWT_SECRET', 'your-secret-key'), // 对称加密密钥 'refresh_ttl' => env('JWT_REFRESH_TTL', 20160), // Token刷新有效期 'password_key' => env('JWT_PASSWORD_KEY', 'password'), // 密码字段名称 'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true), // Token黑名单启用 'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 60), // Token宽限期 'claim' => [], // 自定义Claims ], ];
3. Generate and parse JWT Token
First, we need to generate a JWT Token. Introduce the HyperfJwtJwt
class into the controller and generate Token through the make()
method. The sample code is as follows:
<?php declare(strict_types=1); namespace AppController; use HyperfDiAnnotationInject; use PsrHttpMessageResponseInterface; class AuthController extends AbstractController { /** * @Inject * @var HyperfJwtJwt */ private $jwt; public function login(): ResponseInterface { // 对用户进行验证,验证通过后生成Token $userId = 1; $token = $this->jwt->make(['user_id' => $userId]); return $this->response->json([ 'token' => $token->toString(), 'expires_at' => $token->getClaim('exp'), ]); } }
Next, we need to verify the JWT Token in the middleware and parse out the user information. Introduce the HyperfJwtMiddlewareJwtMiddleware
class into the middleware, and use the handle()
method for verification and parsing. The sample code is as follows:
<?php declare(strict_types=1); namespace AppMiddleware; use HyperfDiAnnotationInject; use HyperfHttpServerContractRequestInterface; use HyperfHttpServerContractResponseInterface as HttpResponse; use HyperfUtilsContext; use HyperfUtilsStr; use HyperfJwtExceptionTokenValidException; use HyperfJwtJwtInterface; use PsrContainerContainerInterface; class JwtMiddleware { /** * @Inject * @var HyperfJwtJwt */ private $jwt; /** * @var JwtInterface */ private $jwtFactory; /** * @var RequestInterface */ private $request; /** * @var HttpResponse */ private $response; public function __construct(ContainerInterface $container, JwtInterface $jwt, RequestInterface $request, HttpResponse $response) { $this->jwtFactory = $jwt; $this->request = $request; $this->response = $response; } public function handle($request, Closure $next) { $token = Str::replaceFirst('Bearer ', '', $this->request->header('Authorization')); // 从Header中获取Token if (empty($token)) { throw new TokenValidException('Token not provided'); } try { $token = $this->jwtFactory->parse($token); // 解析Token $claims = $token->claims(); // 获取Token中的声明 Context::set('user_id', $claims->get('user_id')); // 设置用户ID到上下文 } catch (TokenValidException $e) { throw new TokenValidException('Invalid token', $e->getCode(), $e); } return $next($request); } }
4. Use middleware for authentication
Use middleware in routing for JWT authentication. Open the config/routes.php
file and add the following routing and middleware configuration items:
<?php use AppMiddlewareJwtMiddleware; Router::addGroup('/api', function () { Router::post('/login', 'AppControllerAuthController@login'); // 需要认证的路由 Router::addGroup('/auth', function () { Router::get('/info', 'AppControllerAuthController@info'); }, ['middleware' => [JwtMiddleware::class]]); });
In the above example, AppControllerAuthController@info
requires authentication interface. This interface can only be successfully accessed when carrying a valid JWT Token.
Conclusion:
This article introduces how to use the Hyperf framework for JWT authentication and provides relevant configuration and code examples. Through JWT authentication, we can achieve higher security and user verification functions in the Hyperf framework. I hope this article will be helpful to you when using the Hyperf framework for JWT authentication.
The above is the detailed content of How to use Hyperf framework for JWT authentication. For more information, please follow other related articles on the PHP Chinese website!