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 !

4

3 回答 3

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);
于 2015-05-21T01:33:18.810 回答
6

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.

于 2019-01-17T19:14:17.407 回答
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);
    }
}
于 2018-07-23T19:23:13.357 回答