From 0d7a82ce827aadf7348e3e0605acd6accbdd935b Mon Sep 17 00:00:00 2001 From: "453530270@qq.com" Date: Tue, 8 Oct 2024 09:43:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9jwt=E6=9C=8D=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/controller/Index.php | 32 ++++++++++++++++++++++++++++++++ app/api/service/JWTService.php | 20 +++++++++++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/app/api/controller/Index.php b/app/api/controller/Index.php index 0a25dea..d5bd9d9 100644 --- a/app/api/controller/Index.php +++ b/app/api/controller/Index.php @@ -5,6 +5,13 @@ namespace app\api\controller; use app\BaseController; use app\Request; +// for jwt +use Lcobucci\JWT\Parser; +use Lcobucci\JWT\Builder; +use Lcobucci\JWT\Signer\Hmac\Sha256; +use Lcobucci\JWT\Signer\Key\InMemory; +use Lcobucci\JWT\Token; + class Index extends BaseController { // @@ -39,4 +46,29 @@ class Index extends BaseController } return $salt; } + + public function test(){ + // return time(); + // throwError('密码错误'); + $claims=[ + "id" => 1, + "nick_name" => 'zhangsan' + ]; + $signer = new Sha256(); + $key = InMemory::plainText(config('jwt.secret')); + + // 设置发行时间和过期时间 + $now = time(); + $token = $builder + ->issuedAt($now) // iat: 发行时间 + ->expiresAt($now + config('jwt.token_ttl')) // exp: 过期时间 + ->withClaim('iss', 'xtt') // iss: 发行人 + ->withClaim('sub', 'xtoken') // sub: 主题 + ->withClaim('aud', 'ttc'); // aud: 受众 + foreach ($claims as $key => $value) { + $token = $token->withClaim($key, $value); + } + + return (string) $token->sign($signer, $key); + } } \ No newline at end of file diff --git a/app/api/service/JWTService.php b/app/api/service/JWTService.php index 459e6ee..baf2556 100644 --- a/app/api/service/JWTService.php +++ b/app/api/service/JWTService.php @@ -1,6 +1,7 @@ secret); - $token = (new Builder())->issuedNow()->canOnlyBeUsedAfter(0)->expiresAt(time() + config('jwt.token_ttl')); + $builder = new Builder(); + // 设置发行时间和过期时间 + $now = time(); + $token = $builder + ->issuedAt($now) // iat: 发行时间 + ->expiresAt($now + config('jwt.token_ttl')) // exp: 过期时间 + ->withClaim('iss', 'your_issuer') // iss: 发行人 + ->withClaim('sub', 'your_subject') // sub: 主题 + ->withClaim('aud', 'your_audience'); // aud: 受众 + + // 添加自定义 Claims foreach ($claims as $key => $value) { $token = $token->withClaim($key, $value); } - return (string) $token->sign($signer, $key); + // 构建并签名 Token + $signedToken = $token->sign($signer, $key); + + return (string) $signedToken; } public function verifyToken(string $token): array @@ -39,7 +53,7 @@ class JWTService return $token->getClaims(); } } catch (\Exception $e) { - // Handle exception + // 处理异常 } return [];