Thinkphp6 使用JWT 实现无痛刷新访问令牌

想要实现token无感刷新令牌的方法有很多种,前后端都可以进行控制,今天主要给大家说的是使用后端Thinkphp来进行实现无感刷新令牌

想要实现token无感刷新令牌的方法有很多种,前后端都可以进行控制,今天主要给大家说的是使用后端Thinkphp来进行实现无感刷新令牌

这次使用的是thans/tp-jwt-auth 包。支持Header、Cookie、Param等多种传参方式。包含验证并且自动刷新等多种中间件。

token默认有效期为60秒,如果需要修改请修改env文件。 refresh_ttl为刷新token有效期参数,单位为分钟。默认有效期14天。 token过期后,旧token将会被加入黑名单。 如果需要自动刷新,请使用中间件 thans\jwt\middleware\JWTAuthAndRefresh::class, 自动刷新后会通过header返回,请保存好。(注意,此中间件过期后第一次访问正常,第二次进入黑名单。)

安装

composer require thans/tp-jwt-auth

生成jwt.php,并且.env中会随机生成secret

php think jwt:create

使用

创建用户认证中间件:

php think make:middleware JWT
<?php
 
declare (strict_types=1);
 
namespace app\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验证刷新token机制
 */
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,会将旧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) { // 捕获黑名单,退出登录或者已经自动刷新,当前token就会被拉黑
            throw new HttpException(401, '未登录..');
        }
 
        // 可以获取payload里自定义的字段,比如uid
        $request->uid = $payload['uid']->getValue();
 
        $response = $next($request);
 
        // 如果有新的token,则在响应头返回(前端判断一下响应中是否有 token,如果有就直接使用此 token 替换掉本地的 token)
        if (isset($token)) {
            $this->setAuthentication($response, $token);
        }
 
        return $response;
    }
}

在路由中使用中间件

Route::group(function () {
    Route::get('user', 'user/index');
})->middleware(\app\middleware\JWT::class);

Token生成

......
// 登录逻辑省略
$user = xxxx;
// 生成token,参数为用户认证的信息,请自行添加
$token = JWTAuth::builder(['uid' => $user->id]);
return [
    'token' => 'Bearer ' . $token
];
......

vue前端自定义响应拦截器

axios.interceptors.response.use((response) => {
    // 判断响应中是否有token,如果有则使用此token替换掉本地的token
    this.refreshToken(response);
    return response
}, (error) => {
    // 判断错误响应中是否有token,如果有则使用此token替换掉本地的token
    this.refreshToken(error.response);
    switch (error.response.status) {
        // http状态码为401,则清除本地的数据并跳转到登录页面
        case 401:
            localStorage.removeItem('token');
            console.log('需要重新登录')
            break;
        // http状态码为400,则弹出错误信息
        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);
        }
    }
}

以上这篇thinkphp6 使用JWT 实现无痛刷新访问令牌就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持芦苇派。

原创文章,作者:ECHO陈文,如若转载,请注明出处:https://www.luweipai.cn/php/1658974826/

  • 3