2016-09-07 133 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(); 
} 

}