LeviJames
LeviJames

Reputation: 188

Laravel Tymon\JWT Auth: Check for Outstanding Valid Token Before Authentication?

I'm trying to implement token-based authentication in Laravel 5.5 using Tymon's JWTAuth. I followed the GitHub Documentation for the library and am using the following authentication flow. Here is the authentication portion of my login route:

try {

    // attempt to verify the credentials and create a token for the user
    if (!$token = JWTAuth::attempt($credentials)) {
        return response()->json(['success' => false, 'error' => 'Invalid Credentials. Please make sure you entered the right information and you have verified your email address.'], 401);
    }

} 

catch (JWTException $e) {
    // something went wrong whilst attempting to encode the token
    return response()->json(['success' => false, 'error' => 'could_not_create_token'], 500);
}

// all good so return the token
return response()->json(['success' => true, 'data'=> [ 'token' => $token ]]);

And here are the routes:

Route::group([

    'middleware' => ['jwt.auth', 'jwt.refresh'],

    ], 

    function () {

        // Routes requiring authentication
        Route::get('/logout', 'Auth\LoginController@logout');
        Route::get('/protected', function() {
            return 'This is a protected page. You must be logged in to see it.';
    });

});

So you can see I am using the jwt.auth and jwt.refresh middlewares. Now, everything is seemingly working as expected and I can authenticate users with tokens. Each token has a lifespan of one use and I am provided another valid token after each request (the refresh flow).

However, my problem is that if I have a valid token for a user that has not been used yet, and then I remove it from the header and hit the /login route with valid credentials, I am issued another valid token. So now I have two valid tokens that can be used to authenticate a user, as my /login route is not invalidating previously issued tokens.

Does anyone know of a way to check to see if a user has an outstanding valid token, so that it can be invalidated if the user logs in from elsewhere?

Upvotes: 0

Views: 1879

Answers (1)

LeviJames
LeviJames

Reputation: 188

I'll answer my own question after doing some research. From my understanding, JWT tokens are valid unless explicitly blacklisted. As long as the server recognizes that it itself created the token, then it can decipher the token using a secret key and assume that it's valid. That's why token lifetimes are so important. So if you want to invalidate an issued token, you'd either have to wait for expiry or blacklist it.

Upvotes: 0

Related Questions