TP6 JWT封装

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,
];

3、在登录出生成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);
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}]

你可能感兴趣的:(入门,postman,测试工具,前端)