关于jwt续签的一点小疑问

tymon/jwt-auth这个组件的源码,发现在刷新token的时候,新token的签发时间还是用的原token的。比如我把refresh_ttl设置成一小时,30分钟刷新一次token,那一小时之后就必须重新登录了。

protected function buildRefreshClaims(Payload $payload)
    {
        // Get the claims to be persisted from the payload
        $persistentClaims = collect($payload->toArray())
            ->only($this->persistentClaims)
            ->toArray();

        // persist the relevant claims
        return array_merge(
            $this->customClaims,
            $persistentClaims,
            [
                'sub' => $payload['sub'],
                'iat' => $payload['iat'],
            ]
        );
    }
public function validateRefresh($refreshTTL)
    {
        if ($this->isPast($this->getValue() + $refreshTTL * 60)) {
            throw new TokenExpiredException('Token has expired and can no longer be refreshed');
        }
    }
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
陈先生


<?php

namespace App\Http\Middleware;


use App\Exceptions\CommonException;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\JWTAuth;

// 注意,我们要继承的是 jwt 的 BaseMiddleware
class RefreshTokenMiddleware
{

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws CommonException
     * @throws JWTException
     */
    public function handle($request, Closure $next, $guard = 'api')
    {
        config()->set('auth.defaults.guard', $guard);

        try {
            if ($userInfo = \Tymon\JWTAuth\Facades\JWTAuth::parseToken()->authenticate()) {
                return $next($request);
            }
            throw new CommonException(CommonException::USER_IS_NEED_LOGIN);
        } catch (TokenExpiredException $exception) {
            try {
                $token = \Tymon\JWTAuth\Facades\JWTAuth::parseToken()->refresh();
                auth($guard)->onceUsingId(\Tymon\JWTAuth\Facades\JWTAuth::manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                $response = $next($request);
                $response->headers->set('Authorization', 'Bearer ' . $token);

                return $response;
            } catch (JWTException $exception) {
                throw new CommonException(CommonException::USER_IS_NEED_LOGIN);
            }
        } catch (\Exception $exception) {
            throw new CommonException(CommonException::USER_IS_NEED_LOGIN);

        }

    }
}
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!