关于 jwt 刷新的疑惑
版本 laravel 5.7 + jwt 1.0.r3
环境 nginx + php 7.2 + mysql + redis
对比官方提供的中间件 和 论坛内探讨刷新的中间件 测试得出以下两种 刷新中间件的方法
继承错误基类 BaseMiddleware
完事就 JWTException
能抓到错误信息TokenExpiredException
, TokenBlacklistedException
之类的一点感觉都没有
方法1
public function handle($request, Closure $next)
{
// 检查此次请求中是否带有 token,如果没有则抛出异常。
$this->checkForToken($request);
// 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException 异常
try {
// 检测用户的登录状态,如果正常则通过
if ($this->auth->parseToken()->authenticate()) {
return $next($request);
}
throw new UnauthorizedHttpException('jwt-auth', '未登录');
} catch (TokenExpiredException $exception) {
// 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
try {
// 刷新用户的 token
$token = $this->auth->refresh();
// 使用一次性登录以保证此次请求的成功 ps:自己测试的结果中没影响什么
auth('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
} catch (JWTException $exception) {
// 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
}
}
// 在响应头中返回新的 token
return $this->setAuthenticationHeader($next($request), $token);
}
方法2
public function handle($request, Closure $next)
{
$this->checkForToken($request);
try {
if ($this->auth->parseToken()->authenticate()){
return $next($request);
}
$token = $this->auth->parseToken()->refresh();
} catch (JWTException $e) {
throw new UnauthorizedHttpException('jwt-auth', "请重新登录", $e, $e->getCode());
}
$response = $next($request);
// Send the refreshed token back to the client.
return $this->setAuthenticationHeader($response, $token);
}
疑惑
参考文章 使用 Jwt-Auth 实现 API 用户认证以及无痛刷新访问令牌
客户端检测到 response
是否存在新的 Authorization
然后再去请求一次吗? 恳请大佬指点
推荐文章: