2016-09-07 75 views
0

在Laravel 5中,如果用户的基本身份验证失败,则返回的默认消息是“Invalid Credentials”错误字符串。当这种情况发生时,我试图返回一个自定义的JSON错误。Laravel 5基本身份验证自定义错误

我可以在vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php中编辑返回的响应。但是我还没有看到可以在供应商目录之外更改此消息的行为。有没有办法?

看起来有一些方法,通过Laravel 4要做到这一点:Laravel 4 Basic Auth custom error

回答

0

想通了,貌似我不得不创建自定义的中间件来处理这个问题。 请注意,当从我的浏览器调用我的API时,只有从邮递员这样的工具调用API时,此解决方案才起作用。出于某种原因,当从我的浏览器中调用它时,我总是在看到基本身份验证提示之前出现错误。

在我的控制,我改变了中间件到我的新创建的一个:

$this->middleware('custom'); 

在内核添加我的位置吧:

protected $routeMiddleware = [ 
    'auth.basic.once' => \App\Http\Middleware\Custom::class, 
] 

然后,我创建的中间件。我使用无状态基本身份验证,因为我创建了一个API:

<?php 
namespace App\Http\Middleware; 

use Auth; 
use Closure; 
use Illuminate\Http\Request as HttpRequest; 
use App\Entities\CustomErrorResponse 
class Custom 
{ 
    public function __construct(CustomErrorResponse $customErrorResponse) { 
     $this->customErrorResponse = $customErrorResponse 
    } 
    public function handle($request, Closure $next) 
    { 
     $response = Auth::onceBasic(); 

     if (!$response) { 
      return $next($request); 
     } 
     return $this->customErrorResponse->send(); 
} 

}