处理 laravel 中的 jwt 身份验证错误

Posted

技术标签:

【中文标题】处理 laravel 中的 jwt 身份验证错误【英文标题】:Handle jwt auth errors in laravel 【发布时间】:2018-09-13 23:32:40 【问题描述】:

我正在做一个休息 api 项目。 我正在努力解决一个问题。当我收到令牌过期错误时,生成的代码将是这样的:

public function authenticate(Request $request)
    $this->checkForToken($request);

    try 
        if (! $this->auth->parseToken()->authenticate()) 
            throw new UnauthorizedHttpException('jwt-auth', 'User not found');
        
     catch (JWTException $e) 
        throw new UnauthorizedHttpException('jwt-auth', $e->getMessage(), $e, $e->getCode());
    

这段代码写在这个文件里:

vendor/tymon/jwt-auth/src/Http/Middleware/BaseMiddleware.php

如何将其作为 JSON 类型返回?

【问题讨论】:

return response()->json(["type" => 'jwt-auth', "message" => $e->getMessage()]) 或者使用json_encode($e->getMessage()) 并将其返回到视图或任何地方 【参考方案1】:

在您的 App\Exceptions\Handler 类的渲染方法中捕获该异常并返回格式为 json 的响应:

// Handler.php
// import the class of the exception you want to render a json response for at the top
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
...

public function render($request, Exception $exception)
   

  // if your api client has the correct content-type this expectsJson() 
  // should work. if not you may use $request->is('/api/*') to match the url.


  if($request->expectsJson()) 
  

    if($exception instanceof UnauthorizedHttpException) 

      return response()->json('Unauthorized', 403);

    

  

  return parent::render($request, $e);


【讨论】:

你的异常类是什么意思我默认有这个代码:使用异常;使用 Illuminate\Foundation\Exceptions\Handler 作为 ExceptionHandler; 您需要导入将在渲染方法中使用的异常。所以在你的情况下,将use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; 添加到 Handler.php 的顶部 没有完全帮助,但帮助我了解发生了什么,谢谢 2 U

以上是关于处理 laravel 中的 jwt 身份验证错误的主要内容,如果未能解决你的问题,请参考以下文章

Laravel:实现 JWT 身份验证时出错

Laravel JWT 身份验证错误

每次我输入错误密码时,使用 JWT 身份验证的 Laravel 多重身份验证

JWT 身份验证 Laravel

Laravel 未检测到标头和 JWT 包中发送的身份验证令牌

为啥在 Heroku 服务器上为 Laravel JWT 身份验证收到此错误