Laravel and jwt-auth - how to check if a user is registered

I installed Laravel using jwt (using jwt-auth). In my Kernel.php - $ routeMiddleware, I added:

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

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

In my one-page ajax application, I need to check if the user is logged in, so I 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 by calling JWTAuth :: refresh ($ token), it crashes.

I assume this has something to do with the token being updated.

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

Removing 'jwt-refresh' doesn't seem to solve the problem for us.

!

+4
1

: ? ? , jwt api, , , - :

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
        }
    }

, :

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

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

, - . , , Laravel.

, :)

+2

Source: https://habr.com/ru/post/1659657/


All Articles