tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.31k stars 1.54k forks source link

token refresh bug #2017

Open CcSimple opened 4 years ago

CcSimple commented 4 years ago

Refresh token bug.

when use refresh function, get user Always return null。 eg: $token = auth($guard)->refresh();
$user = auth($guard)->user();

Token is available after refresh,But unable to get the user。

When use setToken,It can get user。

eg: $token = auth($guard)->refresh();
auth($guard)->setToken($token); $user = auth($guard)->user();

I think the problem can be fixed here, Because after the token is refreshed, the current token is not refreshed

https://github.com/tymondesigns/jwt-auth/blob/d4cf9fd2b98790712d3e6cd1094e5ff018431f19/src/JWT.php#L101-L108

Before returning a new token, you need to set the token first

Your environment

Q A
Bug? yes
New Feature? yes
Framework Laravel
Framework version 7.22.2
Package version 1.0
PHP version 7.2.5
bert-w commented 4 years ago

I've noticed the same thing. Thanks for the fix as well.

sotoh commented 4 years ago

Nice trick @CcSimple , I realized today about that, I follow this guide and my tokens worked with the following:

// Added this temporary function, because createNewToken() also works with Auth::attempt
protected function refreshWithToken($token)
   {
        Auth::setToken($token);//<- This code because the bug.
        return response()->json([
           'token' => $token,
           'token_type' => 'bearer',
           'expires_in' => Auth::factory()->getTTL() * 60,
           'user' => Auth::user()
       ], 200);
   }

So for refresh I use this

public function refresh()
    {
        // return $this->createNewToken(Auth::refresh());
        return $this->refreshWithToken(Auth::refresh());
    }
Mexidense commented 3 years ago

I've fixed that using a custom middleware: https://github.com/tymondesigns/jwt-auth/issues/2056#issuecomment-742560435