Shadi Hariri
Shadi Hariri

Reputation: 197

laravel JWT token can be used just once and it gets invalid token on second try

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

});

Upvotes: 0

Views: 1892

Answers (1)

Mathew Tinsley
Mathew Tinsley

Reputation: 6966

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.

Upvotes: 2

Related Questions