How to configure Laravel’s Auth.Basic to accept another authentication field?

Asked

Viewed 688 times

0

I’m using the Laravel 5 and I want to use the middleware auth.basic. But in my database, the table used for authentication (usuarios), doesn’t have the field email, and yes username - the standard expected by Laravel 5 is email.

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

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

I’ve searched Stackoverflow in English, in the documentation and looked at the source code, and so far I haven’t found a solution.

Does anyone know a simple way to set up middleware of auth.basic in order to authenticate Basic?

  • 2

    See if this helps: http://stackoverflow.com/questions/30362295/laravel-5-how-to-use-basic-auth-with-username-in-place-of-email

  • @Miguel that’s right :D

1 answer

1


As stated in the @Miguel user comment, to solve the problem you need to create a new Middleware, containing the validation needed to log in via Auth Basic.

1) First it is necessary to create the Middleware new. Run the following command:

php artisan make:middleware AuthBasic

2) Then add the following validation in Middleware servant:

namespace App\Http\Middleware;

use Closure;

class AuthBasic
{

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

Note that in the method basic, I went on to string "username". This is because, by default, in the method SessionGuard::basic(), we have the value "email" defined by default.

See the method source code basic in the archive SessionGuard.php:

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) Configure your new Middleware, adding it to the Http/Kernel.php. You must replace the Intel auth.basic and add your Auth Basic Middleware - which is on the property $routeMiddleware.

Thus:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.