1.使用命令行创建安装插件 https://www.kancloud.cn/sfzl/tp6-jwtauth/248165
composer require thans/tp-jwt-auth
2.更改配置文件 在config/jwt.php
return [ 'secret' => env('JWT_SECRET'), //Asymmetric key 'public_key' => env('JWT_PUBLIC_KEY'), 'private_key' => env('JWT_PRIVATE_KEY'), 'password' => env('JWT_PASSWORD'), //JWT time to live(默认是60) 'ttl' => env('JWT_TTL', 86400), //Refresh time to live 'refresh_ttl' => env('JWT_REFRESH_TTL', 20160), //JWT hashing algorithm 'algo' => env('JWT_ALGO', 'HS256'), //token获取方法优先考虑数组的前值 'token_mode' => ['header', 'cookie', 'param'], ///黑名单后有效期 'blacklist_grace_period' => env('BLACKLIST_GRACE_PERIOD', 10), 'blacklist_storage' => thans\jwt\provider\storage\Tp5::class, ];
三、登录生成token 引入
use thans\jwt\facade\JWTAuth;
/** * 登录接口 * @param Request $request * @return false|string|\think\response\Json * @throws \think\db\exception\DataNotFoundException * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException */ public function login(Request $request){ try { $data = input(); ///独立验证器 validate(\app\homeapi\validate\Login::class)->check($data); $list = Db::name('user')->where('user',$data['user'])->find(); if ($list){ if ($data['pwd']==$list['pwd']){ //参数是用户认证的信息,请自行添加 生成token $token = JWTAuth::builder(['id' => $list['id']]); //记录日志 Log::record($list['id'].登录; return success(200,成功登录token'=>$token]); }else{ abort(2002,密码错误; } }else{ abort(2002,'用户名错误'); } }catch(HttpException $exception){ //fail/success是自己封装的接口格式 return fail(2002,$exception->getMessage()); }catch (ValidateException $e) { // 验证失败 输出错误信息 return fail(2002,$e->getError()); } }
4.使用中间件 将中间件 在路由出使用
Route::group(function (){ #内容展示 Route::any('show','News/shows'); #发布时间 Route::get('time','News/time'); #赞 Route::get('zan','News/zan'); #浏览 Route::get('lan','News/lan'); #热点 Route::get('hot','News/hot'); })->allowCrossDomain()->middleware(\app\api\middleware\Check::class);
<?php declare (strict_types = 1); namespace app\adminapi\middleware; use thans\jwt\exception\TokenInvalidException; use thans\jwt\facade\JWTAuth; use think\Response; class login { /** * 处理请求 * * @param \think\Request $request * @param \Closure $next * @return Response */ public function handle($request, \Closure $next) { try { ///可获得请求中的完整性token字符串 $tokenStr = JWTAuth::token()->get(); //可验证token, 并获取token中的payload部分 $payload = JWTAuth::auth(); return $next($request); }catch (\Error $e){ //fail(common本文件中包装的接口格式) return fail(2002,请先登录; }catch (TokenInvalidException $exception){ return fail(2002,无效Token'); } } }
5、退出登录
public function logout(){ try { //获取token $token = JWTAuth::token()->get(); //放入黑名单 JWTAuth::invalidate($token); return fail('201',退出登录; }catch (\Error $exception){ return fail(202)token值'); } }
6、获取token伪静态配置值 在public/.htaccess
RewriteCond %{HTTP:Authorization} ^(. )$ RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]