Browse Source

jwt中增加用户名字段

master
xyiege 1 year ago
parent
commit
2f10ffe103
  1. 2
      app/api/controller/Passport.php
  2. 38
      app/api/service/UserService.php

2
app/api/controller/Passport.php

@ -27,7 +27,7 @@ class Passport extends ApiController{
} }
return $this->renderSuccess([ return $this->renderSuccess([
'userId' => $userInfo['uid'], 'userId' => $userInfo['uid'],
'token' => $model->getToken($userInfo['uid']) 'token' => $model->getToken($userInfo['uid'],$userInfo['nick_name'])
], ''); ], '');
} }

38
app/api/service/UserService.php

@ -62,24 +62,29 @@ class UserService {
} }
/** /**
* 获取登录的token * 根据uid,nick_name 换取JWT
* @param int $userId * @param int $userId
* @param string $uname
* @return string * @return string
* @throws \Exception
*/ */
public function getToken(int $userId): string public function getToken(int $userId,string $uname): string
{ {
static $token = ''; static $token = '';
if (empty($token)) { if (empty($token)) {
$token = $this->makeToken($userId); $token = $this->makeToken($userId,$uname);
} }
return $token; return $token;
} }
/** /**
* 生成用户认证的token * 生成JWT
* @param int $userId * @param int $userId
* @param string $uname
* @return string * @return string
* @throws \Exception
*/ */
private function makeToken(int $userId): string private function makeToken(int $userId,string $uname): string
{ {
$signer = new Sha256(); $signer = new Sha256();
$key = InMemory::plainText(config('jwt.secret')); $key = InMemory::plainText(config('jwt.secret'));
@ -88,10 +93,25 @@ class UserService {
$now = new DateTimeImmutable(); // 当前时间 $now = new DateTimeImmutable(); // 当前时间
// //
$token = $config->builder() $token = $config->builder()
->issuedAt($now) // iat: 发行时间 // 签发人
->expiresAt($now->add(new \DateInterval('PT' . config('jwt.token_ttl') . 'S'))) // exp: 过期时间 ->issuedBy('https://douyin.xingtongworld.com/')
->withClaim('user_id', $userId) // 自定义声明 // 受众
->getToken($config->signer(), $config->signingKey()); // 签名 ->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(); return $token->toString();
} }
} }
Loading…
Cancel
Save