【问题标题】:Laravel passport custom error message and status code when user unauthorized用户未经授权时的 Laravel 护照自定义错误消息和状态码
【发布时间】:2018-06-09 21:20:45
【问题描述】:

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

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

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

【问题讨论】:

    标签: laravel authentication laravel-5 oauth laravel-passport


    【解决方案1】:

    发生方法不允许的异常是因为您访问了错误的端点。您正在发布到 get 或反之亦然。

    但是,如果您转到 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

    【讨论】:

    • 找不到可以处理的地方。谢谢!
    猜你喜欢
    • 2021-11-30
    • 2019-01-05
    • 2019-02-01
    • 2023-03-22
    • 2017-10-18
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    相关资源
    最近更新 更多