Laravel 5 - 如何使用用户名代替电子邮件的基本身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30362295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5 - how to use basic auth with username in place of email?
提问by Jeremy Belolo
Hello guys !
大家好 !
So in Laravel 4 we could do
所以在 Laravel 4 中我们可以做
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 !
谢谢 !
回答by Ruffles
Create a new custom middleware using the same code as the default one:
使用与默认中间件相同的代码创建一个新的自定义中间件:
and override the default 'email' field like:
并覆盖默认的“电子邮件”字段,例如:
return $this->auth->basic('username') ?: $next($request);
回答by domdambrogia
Using Laravel 5.7, the handle method looks like this:
使用 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);
}
If you look at the function definition, can specify the $field
value.
如果看函数定义,可以指定$field
值。
According to Laravel's documentationyou can provide middleware parameters:
根据 Laravel 的文档,您可以提供中间件参数:
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:
该:,username
语法可能会有点混乱。但是如果你看一下函数定义:
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.
您会注意到在 之后有两个参数$next
。$guard
是null
在默认情况下,我想它仍然空/空,所以我省略了价值,并提供一个空字符串。下一个参数(用逗号分隔,如文档所述)是$field
我想用于基本身份验证的参数。
回答by Mehdi Eskandari
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);
}
}