access_token过期后如何刷新token
Posted
技术标签:
【中文标题】access_token过期后如何刷新token【英文标题】:How to refresh token after the access_token has expired 【发布时间】:2019-05-09 08:59:53 【问题描述】:我在我的 laravel 应用程序中使用 tymondesigns/jwt-auth 包进行身份验证。我的 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');
问题是只要访问令牌未过期,我就只能刷新令牌。但是,如果我想在访问令牌过期后刷新令牌怎么办?现在,当我在令牌到期后点击/refresh
路由时,它只会抛出 TokenExpiredException。访问令牌过期后如何刷新令牌?
【问题讨论】:
您可以发送一个新的令牌并在前端监视令牌并在有变化时在前端更新它。当然任何人都可以传递令牌并篡改它,但是当服务器解析和验证它时它会失效,因为 JWT 无论如何都会将它与 user_id 绑定。 我不明白。我需要一种方法来让我的用户保持登录状态。所以我需要用刷新的令牌更新他们的令牌。问题是访问令牌过期后我无法刷新它。 前端用什么? Angular 还是 html、CSS、javascript? 我的前端是一个 vuejs 应用。我登录用户,获取默认有一个小时到期的访问令牌并将其保存在本地存储中。一小时后,用户进来发现自己未经身份验证。 将代码放入try-catch中,当有TokenExpiredException
时,捕获它并执行JWTAuth::refresh($old_token)
。现在,将生成一个新令牌。将此传递给客户端。由于您将其存储在本地存储中,因此您可以在那里进行if(localStorage.getItem('token') !== received_token) localStorage.setItem(received_token)
【参考方案1】:
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]);
【讨论】:
【参考方案2】:好像有几个issues与包相关
但是,refresh_token
的生命周期与 access_token
不同,您可以在 config/jwt.php
中配置它。
您只需要确保您的refresh_token
也处于活动状态,否则如果两者都过期,则用户必须请求另一个令牌。
另一个技巧是将此密钥设置为null
,然后refresh_token
将拥有无限的生命周期
/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/
'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
【讨论】:
以上是关于access_token过期后如何刷新token的主要内容,如果未能解决你的问题,请参考以下文章