skip to Main Content

I have a Laravel API which i have installed tymon/jwt-auth into … To log the user in and get a token, im using the following;

if (! $token = auth()->attempt($request->only('email', 'password'), true)) {
    throw ValidationException::withMessages([
        'email' => 'Invalid Credentials',
    ]);
}

return new TokenResource([
    'token' => $token,
    'user' => $user,
]);

I also have a refresh token endpoint, which should invalidate the old token and issue a new one. From the docs i have added;

return new TokenResource([
    'token' => auth()->refresh(),
    'user', auth()->user(),
]);

The problem is, when i hit that endpoint with my current token, it does return a new token but the old one still works.

Is there a way to invalidate the token for refresh?

2

Answers


  1. No you cannot manually expire a token after it has been createed. That’s how Token works. If you create token it will be valid until it expire, but you can create for example blacklist of tokens and everytime you refresh token, add to black list the first token, also consider lowering your token life time if it’s low enought, you can rely on auto expire mechanism

    Login or Signup to reply.
  2. As Boorsuk said this is the default behavior. So to achieve your desired result you can blacklist them. When a user tries to use a token, you could check if it’s in the blacklist. If it is, you can reject it.

    You can do this by creating a middleware that checks if the token is blacklisted and apply the middleware to routes that need token validation.

    Middleware:

    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        
        if (TokenBlacklist::where('token', $token)->exists()) {
            return response()->json(['message' => 'Token has been invalidated'], 401);
        }
    
        return $next($request);
    }
    

    However, you should do it only if your system requires it actually.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search