前言 本文主要给大家介绍了关于Laravel用户多字段认证的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 解决方案:
登录字段不超过两个的(简单的解决方案) 登录字段大于或等于三个的(相对复杂一些)
登录字段不超过两个的
我在网上看到一种相对简单解决方案,但是不能解决所有两个字段的验证:
filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'name'
过滤请求中的表单内容,实现区分 username。弊端显而易见,如果另一个不是 email 就抓瞎了……,下面是另一种通用的解决方案:
在 LoginController 中重写 login 方法
public function login(Requests $request) { //假设字段是 email if ($this->guard()->attempt($request->only('email', 'password'))) { return $this->sendLoginResponse($request); }
//假设字段是 mobile if ($this->guard()->attempt($request->only('mobile', 'password'))) { return $this->sendLoginResponse($request); }
//假设字段是 username if ($this->guard()->attempt($request->only('username', 'password'))) { return $this->sendLoginResponse($request); }
return $this->sendFailedLoginResponse($request); }
可以看到虽然能解决问题,但是显然有悖于 Laravel 的优雅风格,卖了这么多关子,下面跟大家分享一下我的解决方案。 登录字段大于或等于三个的(相对复杂一些)
首先需要自己实现一个 IlluminateContractsAuthUserProvider 的实现,具体可以参考 添加自定义用户提供器 但是我喜欢偷懒,就直接继承了 EloquentUserProvider,并重写了 retrieveByCredentials 方法:
public function retrieveByCredentials(array $credentials) { if (empty($credentials)) { return; }
// First we will add each credential element to the query as a where clause. // Then we can execute the query and, if we found a user, return it in a // Eloquent User "model" that will be utilized by the Guard instances. $query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) { if (! Str::contains($key, 'pass/【尽量使用一键安装脚本,要么自己做,要么网上下载或使用我博客的,把时间用在更多的地方,少做重复劳动的事情】/word')) { $query->orWhere($key, $value); } }
return $query->first(); }
注意: 将 $query->where($key, $value); 改为 $query->orWhere($key, $value); 就可以了!
紧接着需要注册自定义的 UserProvider:
class AuthServiceProvider extends ServiceProvider { /**
public function boot() { $this->registerPolicies();
Auth::provider('custom', function ($app, array $config) { // 返回 IlluminateContractsAuthUserProvider 实例...
return new CustomUserProvider(new BcryptHasher(), config('auth.providers.custom.model')); }); } }
最后我们修改一下 auth.php 的配置就搞定了:
'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => AppModelsUser::class, ],
'custom' => [ 'driver' => 'custom', 'model' => AppModelsUser::class, ],/【关于环境方面,我觉得DOCKER是非常合适和快速部署的一个方式】/ ],
将 web 数组的 provider 修改为前面注册的那个 custom
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'custom', ],
'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
现在哪怕你有在多个字段都妥妥的…
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。