前言
使用的是thans/tp-jwt-auth 包。支持Header、Cookie、Param等多種傳參方式。包含驗(yàn)證并且自動(dòng)刷新等多種中間件。
環(huán)境要求
php >= 7.0
thinkphp ^5.1.10 || ^6.0.0
我這里使用的是ThinkPHP6 + PHP7.3
安裝
composer require thans/tp-jwt-auth
執(zhí)行以下命令,將生成jwt.php,并且.env中會(huì)隨機(jī)生成secret,請(qǐng)不要隨意更新secret,也請(qǐng)保障secret安全。
php think jwt:create
使用方式:對(duì)于需要驗(yàn)證的路由或者模塊添加中間件:
thans\jwt\middleware\JWTAuth::class
自定義認(rèn)證中間件
說明:調(diào)用登錄接口,成功則返回token給前端,所有需要用戶認(rèn)證的路由都需要在頭部攜帶此token。(格式:將token加入header,如下:Authorization:bearer token值)
同時(shí),后端會(huì)判斷用戶token是否過期,如果過期了會(huì)刷新token,并且在響應(yīng)header返回新的token給前端,前端需要判斷響應(yīng)header有沒token,如果有,則直接使用此 token 替換掉本地的 token,以此達(dá)到無痛刷新token效果。
創(chuàng)建用戶認(rèn)證中間件:
php think make:middleware JWT
代碼:
<?php
declare (strict_types=1);
namespace app\api\middleware;
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驗(yàn)證刷新token機(jī)制
* Class JWTToken
* @package app\api\middleware
*/
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,會(huì)將舊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) { // 捕獲黑名單,退出登錄或者已經(jīng)自動(dòng)刷新,當(dāng)前token就會(huì)被拉黑
throw new HttpException(401, '未登錄..');
}
// 可以獲取payload里自定義的字段,比如uid
$request->uid = $payload['uid']->getValue();
$response = $next($request);
// 如果有新的token,則在響應(yīng)頭返回(前端判斷一下響應(yīng)中是否有 token,如果有就直接使用此 token 替換掉本地的 token,以此達(dá)到無痛刷新token效果)
if (isset($token)) {
$this->setAuthentication($response, $token);
}
return $response;
}
}
在路由中使用中間件
Route::group(function () {
Route::get('user', 'user/index');
})->middleware(\app\api\middleware\JWT::class);
登錄接口
......
// 登錄邏輯省略
$user = xxxx;
// 生成token,參數(shù)為用戶認(rèn)證的信息,請(qǐng)自行添加
$token = JWTAuth::builder(['uid' => $user->id]);
return [
'token' => 'Bearer ' . $token
];
......
使用Postman進(jìn)行測(cè)試,注意參數(shù)名是:Authorization
image.png
前端自定義響應(yīng)攔截器
axios.interceptors.response.use((response) => {
// 判斷響應(yīng)中是否有token,如果有則使用此token替換掉本地的token
this.refreshToken(response);
return response
}, (error) => {
// 判斷錯(cuò)誤響應(yīng)中是否有token,如果有則使用此token替換掉本地的token
this.refreshToken(error.response);
switch (error.response.status) {
// http狀態(tài)碼為401,則清除本地的數(shù)據(jù)并跳轉(zhuǎn)到登錄頁(yè)面
case 401:
localStorage.removeItem('token');
console.log('需要重新登錄')
break;
// http狀態(tài)碼為400,則彈出錯(cuò)誤信息
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);
}
}
}
前端需要用戶認(rèn)證請(qǐng)求示例
axios.get('xxx', {
headers: {
Authorization: localStorage.getItem('token')
}
}).then(response => {
console.log(response)
}).catch(error => { //請(qǐng)求失敗,error接收失敗原因
console.log(error);
});