I have a Laravel API and I have installed tymon/jwt-auth
. To log in the user and get the token I use the following code:
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 an endpoint for refresh token
which is supposed to invalidate the old token and issue a new one. According to the documentation, I added the following code:
return new TokenResource([ 'token' => auth()->refresh(), 'user' => auth()->user(), ]);
The problem is that when I access the endpoint with the current token, it does return a new token, but the old one is still valid.
Is there a way to invalidate the refresh token?
This is the default behavior. So to achieve your desired results you can blacklist them. When a user tries to use a token, you can check if it is in the blacklist. If so, you can reject it.
You can achieve this by creating a middleware that checks if the token is in the blacklist and apply that middleware to routes that require token validation.
middleware:
However, you should only do this if your system actually requires it.
You cannot manually expire a token after it is created. This is how tokens work. If you create a token it will be valid until it expires, but you can create a blacklist of tokens and every time you refresh the token, add the first token to the blacklist, also consider lowering the token's lifetime (if low enough), you can rely on an automatic expiration mechanism.