Laravel 用户未经授权时护照自定义错误消息和状态代码

Laravel passport custom error message and status code when user unauthorized

我的项目是 Laravel 5.4 上的 运行,我使用 passport 通过 api 和 bearer token 进行身份验证。一切正常,但是当未经授权的用户试图访问需要身份验证的资源时,用户会收到错误消息 405 method not allowed

但我希望响应是 401 unauthorized 。 如何改变这一点,只发送带有消息的响应,而不是异常?我做了研究,但找不到任何东西。我使用标准 laravel 中间件进行授权 auth:api。我的路由在中间件中分组

Route::group(['middleware' => 'auth:api'], function () {
  // these routes should return 401 if user not authenticated
}

Well method not allowed exception happens because you are hitting the wrong endpoint.您正在发布到 get 或 vice verca。

但是,如果您转到 App\Exception 打开 handler.php in render() 方法,您可以修改例外情况,您可以根据需要调整例外情况示例:

public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Auth\AuthenticationException) {
        return response('unauthorized', 401);
    }
    return parent::render($request, $exception);
}

handler() 方法上只需检查 $exception 是否是任何异常对象的实例,如果是,您可以根据需要修改响应。对于 laravel 例外遵循 link