use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenBlacklistException;
use thans\jwt\exception\TokenBlacklistGracePeriodException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\middleware\JWTAuth;
use think\exception\HttpException;
* JWT验证刷新token机制
class JWT extends JWTAuth
* 刷新token
* @param $request
* @param \Closure $next
* @return mixed
* @throws JWTException
* @throws TokenBlacklistException
* @throws TokenBlacklistGracePeriodException
public function handle($request, \Closure $next): object
try {
$payload = $this->auth->auth();
} catch (TokenExpiredException $e) { // 捕获token过期
// 尝试刷新token,会将旧token加入黑名单
try {
$this->auth->setRefresh();
$token = $this->auth->refresh();
$payload = $this->auth->auth(false);
} catch (TokenBlacklistGracePeriodException $e) {
$payload = $this->auth->auth(false);
} catch (JWTException $exception) {
// 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
throw new HttpException(401, $exception->getMessage());
} catch (TokenBlacklistGracePeriodException $e) { // 捕获黑名单宽限期
$payload = $this->auth->auth(false);
} catch (TokenBlacklistException $e) { // 捕获黑名单,退出登录或者已经自动刷新,当前token就会被拉黑
throw new HttpException(401, '未登录..');
// 可以获取payload里自定义的字段,比如uid
$request->uid = $payload['uid']->getValue();
$response = $next($request);
// 如果有新的token,则在响应头返回(前端判断一下响应中是否有 token,如果有就直接使用此 token 替换掉本地的 token)
if (isset($token)) {
$this->setAuthentication($response, $token);
return $response;
在路由中使用中间件
Route::group(function () {
Route::get('user', 'user/index');
})->middleware(\app\middleware\JWT::class);
Token生成
......
// 登录逻辑省略
$user = xxxx;
// 生成token,参数为用户认证的信息,请自行添加
$token = JWTAuth::builder(['uid' => $user->id]);
return [
'token' => 'Bearer ' . $token
......
vue前端自定义响应拦截器
axios.interceptors.response.use((response) => {
// 判断响应中是否有token,如果有则使用此token替换掉本地的token
this.refreshToken(response);
return response
}, (error) => {
// 判断错误响应中是否有token,如果有则使用此token替换掉本地的token
this.refreshToken(error.response);
switch (error.response.status) {
// http状态码为401,则清除本地的数据并跳转到登录页面
case 401:
localStorage.removeItem('token');
console.log('需要重新登录')
break;
// http状态码为400,则弹出错误信息
case 400:
console.log(error.response.data.error);
break;
return Promise.reject(error)
.......
methods: {
// 刷新token
refreshToken(response) {
let token = response.headers.authorization
if (token) {
localStorage.setItem('token', token);
以上这篇thinkphp6 使用JWT 实现无痛刷新访问令牌就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持芦苇派。
原创文章,作者:ECHO陈文,如若转载,请注明出处:https://www.luweipai.cn/php/1658974826/
thinkphp6
laravel自带的Log::info日志功能有限,只能单个文件记录或者按照日期记录。但是在实际开发过程中,经常需要按功能或者特定需求来记录日志。为了方便,我们可以使用Logger自定义封装一些日志功能。
2023年05月04日
474
Laravel Passport 可以在几分钟之内为你的应用程序提供完整的 OAuth2 服务端实现。Passport 是基于由 Andy Millington 和 Simon Hamp 维护的 League OAuth2 server 建立的。
2022年12月04日
898