【问题标题】:Laravel:Error when Implementing JWT authenticationLaravel:实现 JWT 身份验证时出错
【发布时间】:2020-06-26 14:46:10
【问题描述】:

我在尝试通过 Postman 发布 API 以对站点中的用户进行身份验证时遇到错误。

登录功能:

    public function login(Request $request)
    {

     $credentials = $request->only('email', 'password');

     if ($token = $this->guard()->attempt($credentials)) {
        return $this->respondWithToken($token);
     }
     return response()->json(['error' => 'Unauthorized'], 401);

  }

保护功能

  public function guard()
  {
   return Auth::guard();
  }

邮递员显示的错误

"message": "Call to undefined method Tymon\\JWTAuth\\Contracts\\Providers\\Auth::guard()",
"exception": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",

如何解决?

【问题讨论】:

    标签: laravel api jwt postman


    【解决方案1】:

    如果用户插入有效的电子邮件和密码,您可以使用\JWTAuth::attempt 函数获取令牌,例如:

    ....
    
    use Tymon\JWTAuth\Exceptions\JWTException;
    
    ....
    
    try {
                $token = \JWTAuth::attempt($request->only('email', 'password'));
                return $this->respondWithToken($token);
            } catch (JWTException $exception) {
    
                    return response()->json([
                        'status' => false,
                        'data' => null,
                        'message' => 'Could not create token'
                    ]);
    
            }
    

    编辑 1

    您提交的上述答案是正确的。

    尝试将Auth::guard() 替换为Auth::guard('api')

    public function guard()
      {
       return Auth::guard('api');
      }
    

    更多信息there is a similar issue in GitHub for reference

    【讨论】:

    • 我现在试了,但是报错:Method Illuminate\\Auth\\SessionGuard::factory does not exist.
    【解决方案2】:

    使用类似的构造方法

    public function __construct(){
        auth()->setDefaultDriver('api'); 
    }
    

    还有你的登录功能,比如

    public function login(){
    $credentials = request(['email', 'password']);
    
    if(!$token = auth()->attempt($credentials)){
      return response()->json(['error' => 'Incorrect email/password'], 401);
    }
    return $this->respondWithToken($token);
    }
    

    并注释掉你的守卫功能

    【讨论】:

      【解决方案3】:

      我一直面临这个问题。但解决方案是我在密码上使用bcrypt()。

      bcrypt($password);
      

      【讨论】:

        猜你喜欢
        • 2015-01-21
        • 2016-08-17
        • 2020-03-18
        • 2020-01-05
        • 2023-02-24
        • 1970-01-01
        • 2019-01-07
        • 2017-05-13
        • 2020-07-23
        相关资源
        最近更新 更多