access_token过期后如何刷新令牌

时间:2018-12-07 15:07:26

标签: php laravel jwt

我在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。即使访问令牌过期后,如何刷新令牌?

2 个答案:

答案 0 :(得分:0)

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]);
}

答案 1 :(得分:0)

似乎有几个 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),