【问题标题】:Customize laravel sanctum unauthorize response自定义 laravel sanctum 未授权响应
【发布时间】:2021-10-01 14:11:01
【问题描述】:

我在我的项目中使用 laravel sanctum,但我遇到了一个问题。我想自定义 401 响应代码(未经授权)以在令牌无效时返回 JSON,如下所示:

    {
    "data": {
        "code": 401,
        "book": null,
        "success": false,
        "error": {
            "message": "Not authenticated"
        }
    }
}

而不是默认响应:

{
    "message": "Unauthenticated."
}

如何在 laravel sanctum 中实现这一点?提前致谢。

【问题讨论】:

    标签: laravel laravel-8 rest laravel-sanctum


    【解决方案1】:

    Rendering exceptions

    添加到ExceptionHandler@registerapp/Exceptions/ExceptionHandler.php

    $this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Not authenticated'
            ], 401);
        }
    });
    

    【讨论】:

      【解决方案2】:

      您可以覆盖 Authenticate.php 中间件以输出您想要的消息或捕获 AuthorizationException 以在 Exception/Handler 中显示您想要的消息

      public function render($request, Exception $exception)
      {
          if ($exception instanceof AuthorizationException) {
              return response()->json([
               'message' => 'Not authenticated'
              ],401);
          }
      
          return parent::render($request, $exception);
      }
      

      【讨论】:

      • 渲染函数放在哪里?
      • 我认为他的意思是app/Http/Middleware/Authenticate.php
      猜你喜欢
      • 2022-08-07
      • 2023-03-21
      • 2020-08-08
      • 1970-01-01
      • 2021-07-27
      • 2020-07-04
      • 2021-07-02
      • 2021-11-30
      • 2021-01-12
      相关资源
      最近更新 更多