From 2f10ffe103d04c1f2c7aa9ae85b2bb34289a6335 Mon Sep 17 00:00:00 2001 From: "453530270@qq.com" Date: Tue, 8 Oct 2024 12:41:55 +0800 Subject: [PATCH] =?UTF-8?q?jwt=E4=B8=AD=E5=A2=9E=E5=8A=A0=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E5=90=8D=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/api/controller/Passport.php | 2 +- app/api/service/UserService.php | 38 +++++++++++++++++++++++++-------- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/app/api/controller/Passport.php b/app/api/controller/Passport.php index 7aec4cd..c473e46 100644 --- a/app/api/controller/Passport.php +++ b/app/api/controller/Passport.php @@ -27,7 +27,7 @@ class Passport extends ApiController{ } return $this->renderSuccess([ 'userId' => $userInfo['uid'], - 'token' => $model->getToken($userInfo['uid']) + 'token' => $model->getToken($userInfo['uid'],$userInfo['nick_name']) ], ''); } diff --git a/app/api/service/UserService.php b/app/api/service/UserService.php index 1a623fe..2cb79a9 100644 --- a/app/api/service/UserService.php +++ b/app/api/service/UserService.php @@ -62,24 +62,29 @@ class UserService { } /** - * 获取登录的token + * 根据uid,nick_name 换取JWT * @param int $userId + * @param string $uname * @return string + * @throws \Exception */ - public function getToken(int $userId): string + public function getToken(int $userId,string $uname): string { static $token = ''; if (empty($token)) { - $token = $this->makeToken($userId); + $token = $this->makeToken($userId,$uname); } return $token; } + /** - * 生成用户认证的token + * 生成JWT * @param int $userId + * @param string $uname * @return string + * @throws \Exception */ - private function makeToken(int $userId): string + private function makeToken(int $userId,string $uname): string { $signer = new Sha256(); $key = InMemory::plainText(config('jwt.secret')); @@ -88,10 +93,25 @@ class UserService { $now = new DateTimeImmutable(); // 当前时间 // $token = $config->builder() - ->issuedAt($now) // iat: 发行时间 - ->expiresAt($now->add(new \DateInterval('PT' . config('jwt.token_ttl') . 'S'))) // exp: 过期时间 - ->withClaim('user_id', $userId) // 自定义声明 - ->getToken($config->signer(), $config->signingKey()); // 签名 + // 签发人 + ->issuedBy('https://douyin.xingtongworld.com/') + // 受众 + ->permittedFor('https://douyin.xingtongworld.com/') + // JWT ID 编号 唯一标识 + ->identifiedBy($userId) + // 签发时间 + ->issuedAt($now) + // 在1分钟后才可使用 +// ->canOnlyBeUsedAfter($now->modify('+1 minute')) + // 过期时间1小时 + ->expiresAt($now->modify('+1 hour')) + // 自定义uid 额外参数 + ->withClaim('uid', $userId) + ->withClaim('name',$uname) + // 自定义header 参数 + // ->withHeader('foo', 'bar') + // 生成token + ->getToken($config->signer(), $config->signingKey()); return $token->toString(); } } \ No newline at end of file