search

Home  >  Q&A  >  body text

Update tymon/jwt-auth token in Laravel API

<p>I have a Laravel API and I have installed <code>tymon/jwt-auth</code>. To log in the user and get the token I use the following code: </p> <pre class="brush:php;toolbar:false;">if (! $token = auth()->attempt($request->only('email', 'password'), true)) { throw ValidationException::withMessages([ 'email' => 'Invalid Credentials', ]); } return new TokenResource([ 'token' => $token, 'user' => $user, ]); </pre> <p>I also have an endpoint for <code>refresh token</code> which is supposed to invalidate the old token and issue a new one. According to the documentation, I added the following code: </p> <pre class="brush:php;toolbar:false;">return new TokenResource([ 'token' => auth()->refresh(), 'user' => auth()->user(), ]); </pre> <p>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. </p> <p>Is there a way to invalidate the refresh token? </p>
P粉798010441P粉798010441471 days ago586

reply all(2)I'll reply

  • P粉557957970

    P粉5579579702023-08-15 11:18:45

    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:

    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken();
        
        if (TokenBlacklist::where('token', $token)->exists()) {
            return response()->json(['message' => '令牌已失效'], 401);
        }
    
        return $next($request);
    }

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

    reply
    0
  • P粉768045522

    P粉7680455222023-08-15 00:53:41

    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.

    reply
    0
  • Cancelreply