寫(xiě)一個(gè)BaseController 類
基本思路:
1、繼承一個(gè)公共基類,將驗(yàn)證相關(guān)代碼放在基類
2、根據(jù) 孩子類下的notNeedToken 來(lái)決定是否進(jìn)行驗(yàn)證
3、驗(yàn)證失敗后,直接響應(yīng)回來(lái)
這里需要封裝一個(gè)主要代碼:
protected function response($data = [])
{
$type = $this->getResponseType();
$response = Response::create($data, $type);
throw new HttpResponseException($response);
}
如果直接return 返回,是不會(huì)終止執(zhí)行的,而是會(huì)繼續(xù)執(zhí)行到指定的控制器,所以這里的方法仿造了$this->error() 以及 $this->success()方法。
全部代碼文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-608295.html
<?php
namespace app\api\controller;
use think\Controller;
use think\exception\HttpResponseException;
use think\Request;
use think\Response;
class BaseController extends Controller
{
protected $tokenError = ''; // 錯(cuò)誤信息
protected $tokenInfo = null; // 解析出來(lái)的token信息
protected $statusCode = 200;
protected $notNeedToken = [];
public function _initialize()
{
$this->checkToken();
$this->statusCode = $this->tokenError == '' ? 200 : 401;
if (!empty($this->tokenError)) {
$this->response([
'code' => 0,
'msg' => $this->tokenError
]);
}
}
// 檢查token
public function checkToken()
{
$request = Request::instance();
$path = $request->path();
$tokenStr = $request->header('Authorization');
do {
//echo '所有路由都需要執(zhí)行' . $path;
// 不在排除的路由列表當(dāng)中都需要進(jìn)行驗(yàn)證
if (!in_array($path, $this->notNeedToken)) {
if (empty($tokenStr)) {
// 沒(méi)有傳遞token
$this->tokenError = '請(qǐng)先登錄后操作';
break;
}
[$a, $token] = explode(" ", $tokenStr);
// 如果為空 直接返回錯(cuò)誤
if (empty($token)) {
$this->tokenError = '請(qǐng)先登錄后操作';
break;
}
// 進(jìn)入驗(yàn)證操作
$rst = checkToken($token);
if ($rst['code'] == 2) {
$this->tokenError = $rst['msg'];
break;
}
// token本身還沒(méi)有過(guò)期
$this->tokenInfo = $rst['data'];
// 檢查數(shù)據(jù)庫(kù)表當(dāng)中是否已經(jīng)標(biāo)記為過(guò)期了(可能執(zhí)行了退出登錄了)
$appUserToken = model('api/app_user_token');
$rst = $appUserToken::get([
'user_id' => $this->tokenInfo->id,
'token' => $token
]);
// 不存在該信息
if (empty($rst)) {
$this->tokenError = '沒(méi)有該登錄信息';
break;
}
if ($rst['is_overtime'] == 1) {
$this->tokenError = '登錄已過(guò)期';
break;
}
}
} while (0);
}
protected function response($data = [])
{
$type = $this->getResponseType();
$response = Response::create($data, $type);
throw new HttpResponseException($response);
}
}
控制器UserController文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-608295.html
class User extends BaseController
{
//不需要驗(yàn)證token的接口
protected $notNeedToken = [
'api/user/reg',
'api/user/login'
];
}
到了這里,關(guān)于thinkphp5攔截驗(yàn)證token的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!