JWT中的refresh_token

本文探讨了使用JWT(JSON Web Tokens)时遇到的token过期问题。当JWT过期后,通常需要通过refresh_token进行刷新。根据讨论,常规方法是在指定的refresh路径上设置middleware='jwt.refresh',但在实际操作中,这种方法可能导致新token的获取失败。为解决此问题,建议创建新的路由并在控制器中处理刷新逻辑。同时,文章提及了'Event::listen('tymon.jwt.valid')'钩子和全局异常处理的添加,但具体实现仍需进一步研究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考链接:
https://github.com/tymondesigns/jwt-auth/issues/186
https://github.com/tymondesigns/jwt-auth/issues/11

利用JWT处理过期:
1.在普通路径下请求时如果token过期,则客户端再次发出一个请求给服务器到一个设定的refresh路径
2.在该路径下采用middleware = ‘jwt.refresh’,然后在处理函数中:

$token = JWTAuth::getToken();
$newToken = JWTAuth::refresh($token);

经过尝试,以上方法是不行的!!!不能在middleware=’jwt.refresh’下,请求到的新token首先提示不存在,然后又提示进入blacklist了。解决方法是,直接起一个新的路由,然后把上面的代码放到controller的函数中。

这块没弄明白:

// fired when the token could not be found in the request
Event::listen('tymon.jwt.absent');

// fired when the token has expired
Event::listen('tymon.jwt.expired');

// fired when the token is found to be invalid
Event::listen('tymon.jwt.invalid');

// fired if the user could not be found (shouldn't really happen)
Event::listen('tymon.jwt.user_not_found');

// fired when the token is valid (User is passed along with event)
Event::listen('tymon.jwt.valid');

https://github.com/tymondesigns/jwt-auth/issues/61
这里面提到了:Add Event::listen(‘tymon.jwt.valid’) hook in the boot function of the EventServiceProvider.php, like this.

 public function boot(DispatcherContract  $events)
    {
        parent::boot($events);
        Event::listen('tymon.jwt.valid', function($event)
        {
            Auth::setUser($event);
        });
    }

以及这段加全局异常处理,也没太明白:
Add the following code to the render method within app/Exceptions/Handler.php

public function render($request, Exception $e)
{
    if ($e instanceof Tymon\JWTAuth\Exceptions\TokenExpiredException) {
        return response()->json(['token_expired'], $e->getStatusCode());
    } else if ($e instanceof Tymon\JWTAuth\Exceptions\TokenInvalidException) {
        return response()->json(['token_invalid'], $e->getStatusCode());
    }
    return parent::render($request, $e);
}

留待思考

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值