dongyo1959 2017-10-22 11:02
浏览 465
已采纳

laravel JWT令牌只能使用一次,并在第二次尝试时获得无效令牌

I am using JWT token and it worked fine sometime ago. But now when ever I use the token I get the result I want in first try and I check it for the second time (after 2 minutes) and I get invalid token: This is my authenticate code:

  $credentials = $request->only('email', 'password');

    try {
        // verify the credentials and create a token for the user
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        // something went wrong
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    // if no errors are encountered we can return a JWT
    return response()->json(compact('token'));

And this is my web.php file

Route::group(['prefix' => 'api/v1','middleware' => ['cors']], function(){

Route::resource('authenticate', 'AuthenticateController');
Route::post('authenticate', 'AuthenticateController@authenticate');
Route::group(['middleware' => ['jwt.auth', 'jwt.refresh']], function() {
    Route::resource('books', 'BooksController', ['except'=>'store', 'update']);
});

});

  • 写回答

1条回答 默认 最新

  • douhuigang9550 2017-10-22 15:54
    关注

    When you're using refresh tokens (jwt.refresh middleware) this is the intended behavior.

    https://github.com/tymondesigns/jwt-auth/wiki/Authentication

    This middleware will again try to parse the token from the request, and in turn will refresh the token (thus invalidating the old one) and return it as part of the next response. This essentially yields a single use token flow, which reduces the window of attack if a token is compromised, since it is only valid for the single request.

    If you don't want to use refresh tokens, then you can just drop that middleware. If you do want to use refresh tokens, you will need to update the token you use for authentication on every request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?