受auth保护的路由在未经身份验证时返回400错误

时间:2018-04-17 15:26:18

标签: php laravel api exception exception-handling

在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中可见,但问题不同。

为什么我只使用message获得400以上而不是401?

Full code on GitHub

1 个答案:

答案 0 :(得分:0)

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

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

    return redirect()->guest('login');
}