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([
'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 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();
}
}
Loading…
Cancel
Save