tymondesigns / jwt-auth

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

How to get current authenticated user in the current request after refreshing token. #1842

Open Pehotin opened 5 years ago

Pehotin commented 5 years ago
class AuthRefreshToken
{

    public function handle($request, Closure $next)
    {
        try {
            if (!$user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['error' => 'User not found'], 404);
            }
        } catch (TokenExpiredException $e) {
            $token = JWTAuth::getToken();

            // If the token is expired, then it will be refreshed and added to the headers
            try {
                $refreshed = auth()->refresh(true, true);
                $user = JWTAuth::setToken($refreshed)->toUser();

                // Check session token and compare, if not equal, logout (for preventing login from a multiple devices)
                if ($user->session != $token) {
                    Auth::guard()->logout();

                    return response()->json(['error' => 'Could not refresh token'], 410);
                }

                header('Authorization: Bearer ' . $refreshed);
            } catch (JWTException $e) {
                return response()->json(['error' => 'Could not refresh token'], 410);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'Unknown error'], 500);
        }

        // Login the user instance for global usage
        Auth::login($user);

        return  $next($request);
    }
}
class UserController extends Controller
{
    protected $user;

    public function __construct()
    {
        $this->user = Auth::guard()->user();
    }

    public function me()
    {
        return [
            'user' => new UserResource($this->user)
        ];
    }

}

ERROR Trying to get property 'id' of non-object","status_code":500 ....

stoi2m1 commented 4 years ago

This is the method I use to get the Current Authenticated User.

public function getAuthenticatedUser() {
    try {
        if (! $user = JWTAuth::parseToken()->authenticate()) {
            return response()->json(['user_not_found'], 404);
        }
    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
        return response()->json(['token_expired'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
        return response()->json(['token_invalid'], $e->getStatusCode());
    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
        return response()->json(['token_absent'], $e->getStatusCode());
    }
    return $user;
 }
stale[bot] commented 3 years ago

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.