php laravel10中使用refresh_token自动刷新令牌

kgsdhlau  于 2023-11-16  发布在  PHP
关注(0)|答案(1)|浏览(150)

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

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调用包含refresh_token而不是token。我不知道它是如何发生的。我已经完成了中间件的优先级排序

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分钟,只是为了快速测试。

qyzbxkaa

qyzbxkaa1#

问题似乎出在使用旧的承载令牌的后续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

字符串

相关问题