Laravel 5 - 如何使用用户名替代电子邮件的基本身份验证?

Jer*_*olo 4 basic-authentication laravel laravel-5 laravel-middleware

大家好 !

所以在Laravel 4中我们可以做到

Route::filter('auth.basic', function()
{
    return Auth::basic('username');
});
Run Code Online (Sandbox Code Playgroud)

但现在这是不可能的,而且文档并没有给出如何做到的线索.那么有人可以帮忙吗?

谢谢 !

Ruf*_*les 9

使用与默认代码相同的代码创建新的自定义中间件:

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

并覆盖默认的"电子邮件"字段,如:

return $this->auth->basic('username') ?: $next($request);
Run Code Online (Sandbox Code Playgroud)


dom*_*gia 6

使用 Laravel 5.7,handle 方法如下所示:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

如果看函数定义,可以指定$field值。

根据 Laravel 的文档,您可以提供中间件参数:

定义路由时可以指定中间件参数,方法是用 : 分隔中间件名称和参数。多个参数应以逗号分隔:

使用以下内容,我可以指定要在基本身份验证中使用的字段:

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

:,username语法可能会有点混乱。但是如果你看一下函数定义:

public function handle($request, Closure $next, $guard = null, $field = null)
Run Code Online (Sandbox Code Playgroud)

您会注意到在 之后有两个参数$next$guardnull在默认情况下,我想它仍然空/空,所以我省略了价值,并提供一个空字符串。下一个参数(用逗号分隔,如文档所述)是$field我想用于基本身份验证的参数。