【问题标题】:Routes protected by auth return 400 error on unauthenticated受身份验证保护的路由在未经身份验证时返回 400 错误
【发布时间】:2018-09-27 15:40:53
【问题描述】:

在 Laravel 5.6 上,当我调用受 auth:api 中间件保护的路由时,我收到 400 响应错误,而不是我预期的 401。

api.php:

Route::middleware('auth:api')->group(function() {
    //...
}

还有异常处理程序:

 public function render($request, Exception $e)
{
    // If the request wants JSON (AJAX doesn't always want JSON)
    if ($request->wantsJson()) {
        // Define the response
        $response = [
            'errors' => 'Sorry, something went wrong.'
        ];

        // If the app is in debug mode
        if (config('app.debug')) {
            // Add the exception class name, message and stack trace to response
            $response['exception'] = get_class($e); // Reflection might be better here
            $response['message'] = $e->getMessage();
            $response['trace'] = $e->getTrace();
        }

        // Default response of 400
        $status = 400;

        // If this exception is an instance of HttpException
        if ($this->isHttpException($e)) {
            // Grab the HTTP status code from the Exception
            $status = $e->getStatusCode();
        }

        // Return a JSON response with the response array and status code
        return response()->json($response, $status);
    }

    // Default to the parent class' implementation of handler
    return parent::render($request, $e);
}

错误:

{
    "errors": "Sorry, something went wrong.",
    "exception": "Illuminate\\Auth\\AuthenticationException",
    "message": "Unauthenticated.",
    "trace": [Here's the trace]
}

在this answer 中可以看到预期的行为,但问题有所不同。

为什么我得到的是 400 而不是只有 message 的 401?

Full code on GitHub.

【问题讨论】:

    标签: php laravel api exception exception-handling


    【解决方案1】:

    当默认身份验证中间件检查失败时,它会抛出一个AuthenticationException。您可以通过在 Exception\Handler.php 文件中创建 unauthenticated 函数来更改此异常的处理方式,请参见下面的示例。

    protected function unauthenticated($request, AuthenticationException $exception) {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
    
        return redirect()->guest('login');
    }
    

    【讨论】:

    • 谢谢!我希望我不必那样做。错误被捕获并作为 JSON 发送,并且在我的代码中有一个用于设置响应代码的子句。它只是不起作用:P。作为侧节点,验证错误和其他异常也附带400,格式如上...
    • 你现在在哪里设置响应码?
    • If this exception is an instance of HttpException 注意第一个异常处理程序,不是吗?
    • AuthenticationException 不是 HttpException 的实例
    • 是的,我想它可能不是。这是否意味着 laravel 没有原生设置?
    猜你喜欢
    • 1970-01-01
    • 2018-11-13
    • 2018-05-02
    • 2020-10-15
    • 2017-04-24
    • 2013-12-11
    • 2021-03-14
    • 2019-06-14
    • 2021-12-16
    相关资源
    最近更新 更多