在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
块,那些相同的凭据将突然发挥作用。我做错了什么?
答案 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);
}