MikeBergerUS MikeBergerUS - 2 months ago 8
PHP Question

Laravel 5 Basic Auth custom error

In Laravel 5, if basic auth fails for a user then the default message that is returned is an "Invalid Credentials" error string. I am trying to return a custom JSON error when this situation occurs.

I can edit the returned response in vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
however I have not seen where you can change the behavior of this message outside of the vendor directory. Is there a way?

Looks like there were some ways to do this through Laravel 4: Laravel 4 Basic Auth custom error

Answer

Figured it out, looks like I had to create custom middleware to handle this. Note that this solution didn't work when calling my API from my browser, only when calling it from a tool like Postman. For some reason when calling it from my browser I always got the error before seeing the basic auth prompt.

In my controller I changed the middleware to my newly created one:

$this->middleware('custom');

In Kernel I added the location for it:

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

Then I created the middleware. I used Stateless Basic Auth since I'm creating an 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();
 }

}