自定义 laravel sanctum 未授权响应

时间:2021-07-25 07:00:20

标签: laravel laravel-8 restapi laravel-sanctum

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

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

而不是默认响应:

{
    "message": "Unauthenticated."
}

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

2 个答案:

答案 0 :(得分:0)

您可以覆盖 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);
}

答案 1 :(得分:0)

Rendering exceptions

添加到 ExceptionHandler@register app/Exceptions/ExceptionHandler.php

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