laravel - 处理 laravel 中的 jwt auth 错误

标签 laravel api error-handling jwt token


我正在开发一个rest api 项目。
我正在努力解决一个问题。当我收到 token 过期错误时,生成的代码将如下所示:

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 类型返回?

最佳答案

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);

}

关于laravel - 处理 laravel 中的 jwt auth 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49650422/

相关文章:

angularjs - Angular 中全局错误处理的合理方法

c++ - 错误处理 : distinguishing between 'fatal' errors and 'unexpected input' errors

jquery - 你知道这是什么代码类型以及如何用 jQuery 解析它吗?

php - 根据用户的角色和状态登录 laravel

java - 如果我有自己的日历 API,如何指向下一个工作日

使用 Gitlab CI 错误的 Laravel Dusk 测试,无法连接到端口 :9515: Connection refused

java - Java 中有错误处理 API/框架吗?

api - REST API 是否应该反射(reflect)服务器端应用程序架构

php - 当我尝试填充动态下拉列表时出现 SQLSTATE[42000] 错误

php - 自己网站上的 API 内部请求?