如何使用Hyperf框架進(jìn)行JWT認(rèn)證

如何使用Hyperf框架進(jìn)行JWT認(rèn)證

如何使用Hyperf框架進(jìn)行JWT認(rèn)證

引言:
Hyperf是一款基于swoole的高性能協(xié)程框架,提供了豐富的功能和靈活的擴(kuò)展性。JWT(json Web Token)是一種用于認(rèn)證和傳輸信息的開放標(biāo)準(zhǔn)。在本文中,我們將介紹如何在Hyperf框架中使用JWT認(rèn)證,并提供具體的代碼示例。

一、安裝依賴包
首先,我們需要安裝hyperf/jwt和lcobucci/jwt依賴包。可以通過composer進(jìn)行安裝,打開終端運(yùn)行以下命令:

composer require hyperf/jwt lcobucci/jwt

二、配置認(rèn)證信息
在Hyperf框架中,我們需要配置JWT認(rèn)證所需的相關(guān)信息。打開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     {         // 對用戶進(jìn)行驗證,驗證通過后生成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()方法進(jìn)行驗證和解析。示例代碼如下:

<?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')); // 設(shè)置用戶ID到上下文         } catch (TokenValidException $e) {             throw new TokenValidException('Invalid token', $e-&gt;getCode(), $e);         }          return $next($request);     } }

四、使用中間件進(jìn)行認(rèn)證
在路由中使用中間件進(jìn)行JWT認(rèn)證。打開config/routes.php文件,添加如下路由和中間件配置項:

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

在上面的示例中,AppControllerAuthController@info是需要進(jìn)行認(rèn)證的接口。只有在攜帶有效的JWT Token時,才能成功訪問該接口。

結(jié)論:
本文介紹了如何使用Hyperf框架進(jìn)行JWT認(rèn)證,并提供了相關(guān)的配置和代碼示例。通過JWT認(rèn)證,我們可以在Hyperf框架中實現(xiàn)較高的安全性和用戶驗證功能。希望本文對你在使用Hyperf框架進(jìn)行JWT認(rèn)證有所幫助。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊13 分享