Update tymon/jwt-auth token in Laravel API
P粉798010441
P粉798010441 2023-08-14 14:35:54
0
2
378
<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粉798010441
P粉798010441

reply all(2)
P粉557957970

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!