5

Hello guys !

So in Laravel 4 we could do

Route::filter('auth.basic', function()
{
    return Auth::basic('username');
});

But now it's not possible, and the doc doesn't give a clue about how to. So can anyone help ?

Thanks !

Jeremy Belolo
  • 4,319
  • 6
  • 44
  • 88

4 Answers4

10

Create a new custom middleware using the same code as the default one:

https://github.com/laravel/framework/blob/5.0/src/Illuminate/Auth/Middleware/AuthenticateWithBasicAuth.php

and override the default 'email' field like:

return $this->auth->basic('username') ?: $next($request);
Davor Minchorov
  • 2,018
  • 1
  • 16
  • 20
7

Using Laravel 5.7, the handle method looks like this:

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @param  string|null  $field
 * @return mixed
 */
public function handle($request, Closure $next, $guard = null, $field = null)
{
    return $this->auth->guard($guard)->basic($field ?: 'email') ?: $next($request);
}

If you look at the function definition, can specify the $field value.

According to Laravel's documentation you can provide middleware parameters:

Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas:

Using the following I was able to specify my field to use in basic auth:

Route::middleware('auth.basic:,username')->get('/<route>', 'MyController@action');

The :,username syntax might be a little confusing. But if you look at the function definition:

public function handle($request, Closure $next, $guard = null, $field = null)

You will notice there are two paramters after $next. $guard is null by default and I wanted it remain null/empty so I omit the value and provide an empty string. The next parameter (separated by a comma like the documentation says) is the $field I'd like to use for basic auth.

domdambrogia
  • 2,054
  • 24
  • 31
0

This is what I am using

class AuthenticateOnceWithBasicAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return Auth::onceBasic('username') ?: $next($request);
    }
}
-1

You don't have to copy all the code: You also can add this directly to the route like this: 'auth.basic:,username'. Then, instead of the e-mail, the basic auth will use the username. So, you will end up with something like this: Route::middleware('auth.basic:,username')

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 2
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 05 '23 at 06:51