laravel10中使用refresh_token自动刷新Token

问题描述 投票:0回答:1

我创建了一个中间件,下面是它的代码

public function handle(Request $request, Closure $next): Response
    {
        $accessToken = $request->bearerToken();

        if (!$accessToken) {
            $oClient = PassportClient::where('password_client', 1)->firstOrFail();
            $refreshToken = $request->cookie('refreshToken');

            if ($refreshToken) {
                $serverUrl = Config::get('contants.PROJURL');
                $tokenRequest = Request::create($serverUrl . '/oauth/token', 'post', [
                    'grant_type' => 'refresh_token',
                    'refresh_token' => $refreshToken,
                    'client_id' => $oClient->id,
                    'client_secret' => $oClient->secret,
                    'scope' => '',
                ]);
                $response = app()->handle($tokenRequest);

                if ($response->getStatusCode() == 200) {
                    $content = json_decode($response->getContent(), true);
                    $token = $content['access_token'];
                    $refreshToken = $content['refresh_token'];

                    // Now set the new access token for the current request
                    $request->headers->set('Authorization', 'Bearer ' . $token);

                    // Continue the request
                    $response = $next($request);

                    // Attach the new tokens to the response
                    return $response->cookie('token', $token, 1) // Adjust the expiry time as needed
                        ->cookie('refreshToken', $refreshToken, 10080); // Adjust the expiry time as needed
                } else {
                    // Log the error or handle the response as appropriate
                    Log::error('Failed to refresh token: ' . $response->getContent());
                    return response()->json([
                        'status' => 'error',
                        'message' => 'Refresh token failed.',
                    ], $response->getStatusCode());
                }
            } else {
                // Handle the case where no refresh token is present
                return response()->json([
                    'status' => 'error',
                    'message' => 'No refresh token provided.',
                ], 401);
            }
        }

        // Proceed with the request if there is an access token present
        return $next($request);
    }

现在这段代码无法正常工作。使用 cookie 正确设置响应,但请求承载令牌未更新。执行此中间件后执行的 api 调用包含刷新令牌而不是令牌。我不知道这是怎么发生的。我已经做了中间件的优先级排序

protected $middlewarePriority = [
        \App\Http\Middleware\RefreshTokenMiddleware::class,
        \App\Http\Middleware\Authenticate::class,
        \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        \Illuminate\Session\Middleware\AuthenticateSession::class,
        \App\Http\Middleware\CheckUserRole::class,
    ];

请帮帮我。我将访问令牌的过期时间保留为 1 分钟,只是为了快速测试。

php laravel passport.js middleware laravel-10
1个回答
0
投票

问题似乎出在使用旧的不记名令牌的后续 API 调用上。发生这种情况可能是因为传递给 $next($request) 的 $request 对象可能没有更新的令牌。

$request->headers->set('Authorization', 'Bearer ' . $token);    
$response = $next($request);


$newToken = $response->headers->get('newToken');

if ($newToken) {
    $request->headers->set('Authorization', 'Bearer ' . $newToken);
}

// Attach the new tokens to the response as before
© www.soinside.com 2019 - 2024. All rights reserved.