-1

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

Geco
  • 125
  • 12

1 Answers1

2

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,

Tarasovych
  • 1,836
  • 2
  • 12
  • 40
  • Thanks , wich controller , you mean `LoginController` ? – Geco Apr 22 '19 at 14:24
  • @Geco probably.. I don't know where do you handle auth. You've not wrote it in your question. – Tarasovych Apr 22 '19 at 14:24
  • no it dosn't work , it dosn't use the functions of LoginController , i don't know where is its methods , and how it functions , laravel documetation also didn't say anything about it . – Geco Apr 22 '19 at 14:26
  • pay attention , it is `http basic authentication` , not the default `auth` that is included with the laravel – Geco Apr 22 '19 at 14:27
  • i handle `auth` in a `controller` named `LoginController`, I'm pretty efficient at it, but this one, I don't know how this one works! – Geco Apr 22 '19 at 14:30
  • and how should i use it after declaring this class ? sorry i don't fully understand middlewares , but i created one and i overrided the handle method , now how should i use it ? thanks in advance – Geco Apr 22 '19 at 14:53
  • [Register](https://laravel.com/docs/5.8/middleware#registering-middleware) you fresh middleware and assign it to routes you need to be protected by basic auth – Tarasovych Apr 22 '19 at 14:54
  • Basically you want to change `'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,` to `'auth.basic' => \app\Http\Middleware\YourBasicAuthMiddleware::class,` – Tarasovych Apr 22 '19 at 14:55