How do I configure Laravel's Auth.Basic to accept another authentication field?

0

I'm using Laravel 5 and I want to use the auth.basic middleware. But in my database, the table used for authentication ( usuarios ), does not have the email field, but username - the default expected by Laravel 5 is email .

I was able to quietly configure AuthController to authenticate using a custom field. But these settings are not the same for auth.basic , because the following error is being generated when trying to do this type of authentication:

  

Column not found: 1054 Unknown column 'email' in 'where clause'

I have already researched Stackoverflow in English, in the documentation and looked at the source code, and so far I have not found a solution.

Does anyone know a simple way to set middleware of auth.basic to be able to Basic ?

    
asked by anonymous 03.08.2016 / 21:01

1 answer

0

As stated in the comment by @Miguel user, to solve the problem it is necessary to create a new Middleware , containing the necessary validation to log in via Auth Basic .

1) First you need to create% new%. Run the following command:

php artisan make:middleware AuthBasic

2) Then, add the following validation in% created%:

namespace App\Http\Middleware;

use Closure;

class AuthBasic
{

    public function handle($request, Closure $next)
    {
        return auth()->basic('username') ?: $next($request);
    }
}

Note that in the Middleware method, I have passed Middleware basic . This is because, by default, in the string method, we have the "username" value set by default.

See the source code for the SessionGuard::basic() method in the "email" file:

public function basic($field = 'email', $extraConditions = [])
{
    if ($this->check()) {
        return;
    }

    // If a username is set on the HTTP basic request, we will return out without
    // interrupting the request lifecycle. Otherwise, we'll need to generate a
    // request indicating that the given credentials were invalid for login.
    if ($this->attemptBasic($this->getRequest(), $field, $extraConditions)) {
        return;
    }

    return $this->getBasicResponse();
}

3) Set your new basic by adding it to SessionGuard.php . You should replace the Middleware index and add your Auth Basic Middleware - which is in the Http/Kernel.php property.

So:

//'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.basic'  => \App\Http\Middleware\AuthBasic::class,
    
04.08.2016 / 15:37