Search code examples
laravelhttprequestlaravel-authentication

in Laravel HTTP Basic Authentication implementation it uses email for username , how do we change the column to be username?


in laravel we can use Http Basic Authentication to facilitate user login . without having a login page , by attaching middleware->('auth.basic') , to the end of the Route in web.php , but by default it gets email as the username , how may i change it ? thank you .

Route::get('/somePage','Controller@controllerFunction')
->middleware('auth.basic');

picture : https://drive.google.com/file/d/1gbzE0azW8TfZsvQN7k7ZoG2PIRlo14i6/view?usp=sharing


Solution

  • From the docs:

    Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will use the email column on the user record as the "username".

    There is a handle() method inside default middleware.

    You have to create your own middleware and override handle():

    namespace app\Http\Middleware;
    
    use Closure;
    use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
    
    class YourBasicAuthMiddleware extends AuthenticateWithBasicAuth
    {
        public function handle($request, Closure $next, $guard = null, $field = null)
        {
            $this->auth->guard($guard)->basic($field ?: 'YOUR_FIELD'); //place here the name of your field
    
            return $next($request);
        }
    }
    

    Than update your App\Http\Kernel:

    'auth.basic' => \app\Http\Middleware\YourBasicAuthMiddleware::class,