Laravel 和 jwt-auth - 如何检查用户是否登录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40390141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:41:41  来源:igfitidea点击:

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

laraveljwt

提问by Thomas Andersen

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

我已经用 jwt(使用 jwt-auth)设置了 Laravel。在我的 Kernel.php - $routeMiddleware 我添加了:

'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.

据我了解,'jwt.refresh' 会为每个请求自动刷新/为用户创建一个新令牌。

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:

在我的单页 ajax 应用程序中,我需要检查用户是否已登录,因此我添加了一个调用此函数的路由:

  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.

问题是当 isAuthenticated() 被调用时 JWTAuth::refresh($token) 调用失败。

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?

我想要做的是如果客户端的令牌有效则返回 true。有没有办法做到这一点?

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

删除 'jwt-refresh' 似乎不能为我们解决问题。

Thank you in advance!

先感谢您!

采纳答案by Oluwatobi Samuel Omisakin

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:

我的第一个观察是,令牌存储在哪里?它是否与请求一起解析?因为我相信如果您的应用程序将 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
        }
    }

If successfully parsed from the request, then:

如果从请求中成功解析,则:

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

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

见: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.

使用您的示例代码,如果未设置令牌 - 不会检索任何内容。但是,如果您想要基于会话的身份验证,为什么不使用 Laravel 的默认身份验证。

Hope this helps :)

希望这可以帮助 :)

回答by MoadKey

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

您可以获取与令牌相关的当前用户并检查是否为空:

$user = JWTAuth::setToken($token)->toUser();
if($user == null){
abort(401);
}