如何使用Hyperf框架进行JWT认证

如何使用Hyperf框架进行JWT认证

如何使用Hyperf框架进行JWT认证

引言:
Hyperf是一款基于swoole的高性能协程框架,提供了丰富的功能和灵活的扩展性。JWT(json Web Token)是一种用于认证和传输信息的开放标准。在本文中,我们将介绍如何在Hyperf框架中使用JWT认证,并提供具体的代码示例。

一、安装依赖包
首先,我们需要安装hyperf/jwt和lcobucci/jwt依赖包。可以通过composer进行安装,打开终端运行以下命令:

composer require hyperf/jwt lcobucci/jwt

二、配置认证信息
在Hyperf框架中,我们需要配置JWT认证所需的相关信息。打开config/autoload/jwt.php文件,添加如下配置项:

<?php return [     'default' => [         'valid_seconds' =&gt; env('JWT_VALID_SECONDS', 3600), // Token有效期         'secret' =&gt; env('JWT_SECRET', 'your-secret-key'), // 对称加密密钥         'refresh_ttl' =&gt; env('JWT_REFRESH_TTL', 20160), // Token刷新有效期         'password_key' =&gt; env('JWT_PASSWORD_KEY', 'password'), // 密码字段名称         'blacklist_enabled' =&gt; env('JWT_BLACKLIST_ENABLED', true), // Token黑名单启用         'blacklist_grace_period' =&gt; env('JWT_BLACKLIST_GRACE_PERIOD', 60), // Token宽限期         'claim' =&gt; [], // 自定义Claims     ], ];

三、生成和解析JWT Token
首先,我们需要生成JWT Token。在控制器中引入HyperfJwtJwt类,并通过make()方法生成Token。示例代码如下:

<?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-&gt;make(['user_id' =&gt; $userId]);          return $this-&gt;response-&gt;json([             'token' =&gt; $token-&gt;toString(),             'expires_at' =&gt; $token-&gt;getClaim('exp'),         ]);     } }

接下来,我们需要在中间件中验证JWT Token并解析出用户信息。在中间件中引入HyperfJwtMiddlewareJwtMiddleware类,并使用handle()方法进行验证和解析。示例代码如下:

<?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-&gt;request = $request;         $this-&gt;response = $response;     }      public function handle($request, Closure $next)     {         $token = Str::replaceFirst('Bearer ', '', $this-&gt;request-&gt;header('Authorization')); // 从Header中获取Token         if (empty($token)) {             throw new TokenValidException('Token not provided');         }          try {             $token = $this-&gt;jwtFactory-&gt;parse($token); // 解析Token              $claims = $token-&gt;claims(); // 获取Token中的声明             Context::set('user_id', $claims-&gt;get('user_id')); // 设置用户ID到上下文         } catch (TokenValidException $e) {             throw new TokenValidException('Invalid token', $e-&gt;getCode(), $e);         }          return $next($request);     } }

四、使用中间件进行认证
在路由中使用中间件进行JWT认证。打开config/routes.php文件,添加如下路由和中间件配置项:

<?php use AppMiddlewareJwtMiddleware;  Router::addGroup('/api', function () {     Router::post('/login', 'AppControllerAuthController@login');      // 需要认证的路由     Router::addGroup('/auth', function () {         Router::get('/info', 'AppControllerAuthController@info');     }, ['middleware' => [JwtMiddleware::class]]); });

在上面的示例中,AppControllerAuthController@info是需要进行认证的接口。只有在携带有效的JWT Token时,才能成功访问该接口。

结论:
本文介绍了如何使用Hyperf框架进行JWT认证,并提供了相关的配置和代码示例。通过JWT认证,我们可以在Hyperf框架中实现较高的安全性和用户验证功能。希望本文对你在使用Hyperf框架进行JWT认证有所帮助。

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享