Laravel 5.5基本身份验证登录异常

时间:2017-11-08 22:56:29

标签: php laravel laravel-5.5

在Laravel 5.5中,当使用内置的基本身份验证时,失败的登录尝试由laravel/framework/src/Illuminate/Auth/SessionGuard.php处理:

throw new UnauthorizedHttpException('Basic', 'Invalid credentials.');

然而,当关闭调试时,这将返回通用"哎呀,出错了"错误信息。

我尝试编辑异常处理程序(app \ Exceptions \ Handler.php),以便在发生身份验证错误时返回自定义JSON错误。

 /**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{

    //Handle API authentication failure
    if ($exception instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
        return response()->json(['error' => 'Invalid user name or password.'], 401);
    }

    return parent::render($request, $exception);
}

但是,即使用户输入有效凭据,此始终也会返回此错误消息。如果我注释掉if块,那些相同的凭据将突然发挥作用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

响应必须包含相应的标题。

public function render($request, Exception $exception)
{

    //Handle API authentication failure
    if ($exception instanceof \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException) {
        $headers = array('WWW-Authenticate' => 'Basic');
        return response()->json(['error' => 'Invalid user name or password.'], 401);
    }

    return parent::render($request, $exception);
}