https://blog.csdn.net/centaury32/article/details/134997438
按照https://blog.csdn.net/centaury32/article/details/134999029的方法验证登录Token,那么每一步都需要写同样一段代码,这里可以结合中间件进行验证
一、创建中间件:php think make:middleware <应用名>@<文件名>
php think make:middleware admin@AdminLogin
#appp\middleware\AdminLogin.php
<?php
declare (strict_types = 1);namespace app\admin\middleware;class AdminLogin
{/*** 处理请求** @param \think\Request $request* @param \Closure $next* @return Response*/public function handle($request, \Closure $next){//}
}
在中间件文件中写入登录Token验证
#app\admin\middleware\AdminLogin.php
<?php
declare (strict_types = 1);namespace app\admin\middleware;class AdminLogin
{/*** 处理请求** @param \think\Request $request* @param \Closure $next* @return Response*/public function handle($request, \Closure $next){$request_uri = $_SERVER['REQUEST_URI'];$pathinfo = explode('?',$request_uri)[0];$pathinfo = strtolower($pathinfo);$white_list = []; // 白名单,不用登录if(!in_array($pathinfo, $white_list)){// 用户请求Token$token = $request->header('Access-Token');// 验证是否存在tokenif (empty($token)) {return json(['status'=>401,'msg'=>'token为空']);} else {$result = checkToken($token);if ($result['status'] != 200) {return json(['status'=>$result['status'],'msg'=>$result['msg']]);}$request->uid = $result['data']['id']; // 记录用户登录信息,给控制器传参}}return $next($request);}
}
在app\admin\middleware.php文件中调用中间件
#app\admin\middleware.php\app\admin\middleware\AdminLogin::class,
#app\admin\middleware.php<?php
// 这是系统自动生成的middleware定义文件
return [\app\admin\middleware\AdminLogin::class,
];
这样,登录Token验证就生效了,由于没有设置白名单,所以登录接口也被要求需要传Token
在AdminLogin.php中间件中写入白名单
$white_list = ['admin/Passport/login'
];
<?php
declare (strict_types = 1);namespace app\admin\middleware;class AdminLogin
{/*** 处理请求** @param \think\Request $request* @param \Closure $next* @return Response*/public function handle($request, \Closure $next){$request_uri = $_SERVER['REQUEST_URI'];$pathinfo = explode('?',$request_uri)[0];$pathinfo = strtolower($pathinfo);$white_list = ['/admin/passport/login']; // 白名单,不用登录if(!in_array($pathinfo, $white_list)){// 用户请求Token$token = $request->header('Access-Token');// 验证是否存在tokenif (empty($token)) {return json(['status'=>401,'msg'=>'token为空']);} else {$result = checkToken($token);if ($result['status'] != 200) {return json(['status'=>$result['status'],'msg'=>$result['msg']]);}$request->uid = $result['data']['id']; // 记录用户登录信息,给控制器传参}}return $next($request);}
}
这样,登录接口就不需要通过中间件验证Token了
在前面的admin/Index/index接口中代码就可以由图(1)改成图(2):
图(1)
图(2)
使用中间件后就不用每个方法中都写入登录Token验证的代码了