gpt4 book ai didi

php - access_token 过期后如何刷新 token

转载 作者:行者123 更新时间:2023-12-04 12:03:32 29 4
gpt4 key购买 nike

我正在使用 tymondesigns/jwt-auth在我的 Laravel 应用程序中打包以进行身份​​验证。我的 AuthController 看起来像这样:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Contracts\Providers\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;

class AuthController extends Controller {
public $auth;
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('jwt', ['except' => ['login']]);
}

/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$user = \App\User::first();

auth()->byId($user->id);

if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->respondWithToken($token);
}

/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}

/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();

return response()->json(['message' => 'Successfully logged out']);
}

/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
$token = \Auth::guard()->refresh();
$user = JWTAuth::setToken($token)->toUser();
return $this->respondWithToken($token);
}

/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
$responseArray = [
'access_token' => $token,
'user' => new UserResource(auth()->user()),
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
];

return response()->json($responseArray);
}

}

我有一个 JWT 中间件, handle()其方法如下所示:
public function handle($request, Closure $next)
{
JWTAuth::parseToken()->authenticate();
return $next($request);
}

以下是路线:
Route::post('login', 'AuthController@login')->name('login');
Route::post('logout', 'AuthController@logout');
Route::post('refresh', 'AuthController@refresh');

问题是我只能刷新 token ,只要访问 token 没有过期。但是如果我想在访问 token 过期后刷新 token 怎么办?现在,当我点击 /refresh 时它只会抛出 TokenExpiredException token 到期后的路由。即使访问 token 已过期,我如何刷新 token ?

最佳答案

public function token(){
$token = JWTAuth::getToken();
if(!$token){
throw new BadRequestHtttpException('Token not provided');
}
try{
$token = JWTAuth::refresh($token);
}catch(TokenInvalidException $e){
throw new AccessDeniedHttpException('The token is invalid');
}
return $this->response->withArray(['token'=>$token]);
}

关于php - access_token 过期后如何刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53672154/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com