上一篇
<?php namespace App\Http\Middleware; use Tymon\JWTAuth\Exceptions\TokenExpiredException; class RefreshToken extends \Tymon\JWTAuth\Http\Middleware\BaseMiddleware { public function handle($request, Closure $next) { try { return parent::handle($request, $next); } catch (TokenExpiredException $e) { $token = $this->auth->refresh(); // 🔄 刷新Token return $this->setAuthenticationHeader($next($request), $token); } } }
// routes/api.php Route::group(['middleware' => ['token.refresh', 'auth:api']], function () { Route::get('/user', 'UserController@info'); });
JWT_TTL=120 # Token有效期2小时 JWT_REFRESH_TTL=20160 # 刷新期2周(120*24*7) JWT_BLACKLIST_ENABLED=true # 启用黑名单 JWT_BLACKLIST_GRACE_PERIOD=600 # 宽限时间10分钟
axios.interceptors.response.use( response => response, async error => { if (error.response.status === 401) { try { const { data } = await axios.post('/api/refresh'); localStorage.setItem('token', data.token); // 💾 存储新Token error.config.headers.Authorization = `Bearer ${data.token}`; return axios(error.config); // 🔁 重试原请求 } catch (refreshError) { window.location.href = '/login'; // 🚪 刷新失败跳转 } } return Promise.reject(error); } );
let isRefreshing = false; axios.interceptors.response.use(..., async (error) => { if (error.response.status === 401 && !isRefreshing) { isRefreshing = true; // 🔒 上锁,其他请求等待 const { data } = await axios.post('/api/refresh'); // 📢 通知所有等待的请求更新Token ... isRefreshing = false; } });
// 后端设置Cookie return response()->json(['token' => $token]) ->cookie('jwt_token', $token, 43200, null, null, true, true);
// 每次刷新检查Redis if (Redis::incr('refresh_count:' . $userId) > 5) { abort(429, '刷新太频繁啦!'); }
test('token自动续签', function () { $user = User::factory()->create(); $response = $this->actingAs($user)->get('/api/user'); $response->assertJson(['token' => $newToken]); });
💡 提示:2025年记得定期用
composer update
更新包,安全补丁比游戏更新还重要哦!
本文由 业务大全 于2025-08-26发表在【云服务器提供商】,文中图片由(业务大全)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://xdh.7tqx.com/wenda/732529.html
发表评论