Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel and jwt-auth - how to check if the user is logged in

Tags:

laravel

jwt

I have set up Laravel with jwt (using jwt-auth). In my Kernel.php - $routeMiddleware I have added :

'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class

As I understand it 'jwt.refresh' will automatically refresh / create a new token for the user for each request.

In my single page ajax app I need to check if the user is logged in so I have added a route that calls this function:

  public function isAuthenticated() {
    $token = JWTAuth::getToken();
    if(!$token){
      throw new JWTException('Token not provided');
    }
    try{
      $token = JWTAuth::refresh($token);
    }catch(TokenInvalidException $e){
      throw new AccessDeniedHttpException('The token is invalid');
    }
    return $this->response->withArray(['token'=>$token]);
  }

The problem is that when isAuthenticated() is called the JWTAuth::refresh($token) call fails.

I guess it has something to do with that the token is refreshed.

What I want to do is to return true if the client's token is valid. Is there a way to do this?

Removing 'jwt-refresh' seems to not solve the issue for us.

Thank you in advance!

like image 444
Thomas Andersen Avatar asked Nov 02 '16 21:11

Thomas Andersen


2 Answers

My first observation is, where is the token stored? Is it parsed with the request? Because I believe that if your app uses jwt with api, then each request should have a token to signify a logged in user so something like this would be helpful:

try {
        if (! $token = JWTAuth::parseToken()) {
            //throw an exception
        }
    } catch (Exception $e) {
        if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
                            //throw an exception
        }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
                            //throw an exception
        } else if ( $e instanceof \Tymon\JWTAuth\Exceptions\JWTException) {
                            //throw an exception
        }else{
                            //throw an exception
        }
    }

If successfully parsed from the request, then:

$user = JWTAuth::toUser($token);

see: https://github.com/tymondesigns/jwt-auth/wiki/Authentication

With your example code, if the token is not set - nothing is retrieved. However, if you want session based authentication, why not use the default authentication from Laravel.

Hope this helps :)

like image 62
Oluwatobi Samuel Omisakin Avatar answered Oct 19 '22 21:10

Oluwatobi Samuel Omisakin


You can get the current user related to token and check if not null:

$user = JWTAuth::setToken($token)->toUser();
if($user == null){
abort(401);
}
like image 39
MoadKey Avatar answered Oct 19 '22 19:10

MoadKey