laravel修改用户模块的密码验证实现
做项目的时候,用户认证几乎是必不可少的,如果我们的项目由于一些原因不得不使用 users 之外的用户表进行认证,那么就需要多做一点工作来完成这个功能。
现在假设我们只需要修改登录用户的表,表名和表结构都与框架默认的表users不同,文档没有教我们如何去做,但是别慌,稍微看下框架实现用户认证的源码就能轻松实现。
首先,自定义一张表用来登录,表结构和模拟数据如下:
表 admins
id | login_name | login_pass |
---|---|---|
1 | admin | 10$2muhp7b6ghvongb/.b/x6uuew/yl3fqpkjztawrm0u577clf07xda |
从配置文件入手
用户认证相关的配置都保存在config/auth.php文件中,先来看看配置文件的内容:
<?php return [ /* |-------------------------------------------------------------------------- | authentication defaults |-------------------------------------------------------------------------- | | this option controls the default authentication "guard" and password | reset options for your application. you may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | authentication guards |-------------------------------------------------------------------------- | | next, you may define every authentication guard for your application. | of course, a great default configuration has been defined for you | here which uses session storage and the eloquent user provider. | | all authentication drivers have a user provider. this defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | supported: "session", "token" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], /* |-------------------------------------------------------------------------- | user providers |-------------------------------------------------------------------------- | | all authentication drivers have a user provider. this defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | if you have multiple user tables or models you may configure multiple | sources which represent each model / table. these sources may then | be assigned to any extra authentication guards you have defined. | | supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => app\user::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | resetting passwords |-------------------------------------------------------------------------- | | you may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | the expire time is the number of minutes that the reset token should be | considered valid. this security feature keeps tokens short-lived so | they have less time to be guessed. you may change this as needed. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], ];
默认使用的守卫是web,而web守卫使用的认证驱动是session,用户提供器是users。假设我们的需求只是将用户的提供器由users改为admins,那么我们需要做两步操作:
修改默认的用户提供器,将provider=>'users'改为provider=>'admins'
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], ],
配置admins提供器,假设依旧使用eloquent作为驱动,并创建好了admins表的模型
'providers' => [ 'admins' => [ 'driver' => 'eloquent', 'model' => app\admin::class ] ],
使用auth门面的attempt方法进行登录
sessionguard 中的attempt方法:
//illuminate\auth\sessionguard public function attempt(array $credentials = [], $remember = false) { $this->fireattemptevent($credentials, $remember); $this->lastattempted = $user = $this->provider->retrievebycredentials($credentials); // if an implementation of userinterface was returned, we'll ask the provider // to validate the user against the given credentials, and if they are in // fact valid we'll log the users into the application and return true. if ($this->hasvalidcredentials($user, $credentials)) { $this->login($user, $remember); return true; } // if the authentication attempt fails we will fire an event so that the user // may be notified of any suspicious attempts to access their account from // an unrecognized user. a developer may listen to this event as needed. $this->firefailedevent($user, $credentials); return false; }
该方法中调用 userprovider 接口的retrievebycredentials方法检索用户,根据我们的配置,userprovider接口的具体实现应该是eloquentuserprovider,因此,我们定位到eloquentuserprovider的retrievebycredentials方法:
//illuminate\auth\eloquentuserprovider public function retrievebycredentials(array $credentials) { if (empty($credentials) || (count($credentials) === 1 && array_key_exists('password', $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, 'password')) { continue; } if (is_array($value) || $value instanceof arrayable) { $query->wherein($key, $value); } else { $query->where($key, $value); } } return $query->first(); }
该方法会使用传入的参数(不包含password)到我们配置的数据表中搜索数据,查询到符合条件的数据之后返回对应的用户信息,然后attempt方法会进行密码校验,校验密码的方法为:
//illuminate\auth\sessionguard /** * determine if the user matches the credentials. * * @param mixed $user * @param array $credentials * @return bool */ protected function hasvalidcredentials($user, $credentials) { return ! is_null($user) && $this->provider->validatecredentials($user, $credentials); }
进一步查看eloquentuserprovider中的validatecredentials方法
//illuminate\auth\eloquentuserprovider public function validatecredentials(usercontract $user, array $credentials) { $plain = $credentials['password']; return $this->hasher->check($plain, $user->getauthpassword()); }
通过validatecredentials可以看出,提交的认证数据中密码字段名必须是password,这个无法自定义。同时可以看到,入参$user必须实现illuminate\contracts\auth\authenticatable接口(usercontract是别名)。
修改 admin 模型
admin模型必须实现illuminate\contracts\auth\authenticatable接口,可以借鉴一下user模型,让admin直接继承illuminate\foundation\auth\user 就可以,然后重写getauthpassword方法,正确获取密码字段:
// app\admin public function getauthpassword() { return $this->login_pass; }
不出意外的话,这个时候就能使用admins表进行登录了。
larval 5.4的默认auth登陆传入邮件和用户密码到attempt 方法来认证,通过email 的值获取,如果用户被找到,经哈希运算后存储在数据中的password将会和传递过来的经哈希运算处理的passwrod值进行比较。如果两个经哈希运算的密码相匹配那么将会为这个用户开启一个认证session。
参考上面的分析,我们就需要对eloquentuserprovider中的validatecredentials方法进行重写,步骤如下
1. 修改 app\models\user.php 添加如下代码
public function getauthpassword() { return ['password' => $this->attributes['password'], 'salt' => $this->attributes['salt']]; }
2. 建立一个自己的userprovider.php 的实现
<?php namespace app\foundation\auth; use illuminate\auth\eloquentuserprovider; use illuminate\contracts\auth\authenticatable; use illuminate\support\str; /** * 重写用户密码校验逻辑 * class gfzxeloquentuserprovider * @package app\foundation\auth */ class gfzxeloquentuserprovider extends eloquentuserprovider { /** * validate a user against the given credentials. * * @param \illuminate\contracts\auth\authenticatable $user * @param array $credentials * @return bool */ public function validatecredentials(authenticatable $user, array $credentials) { $plain = $credentials['password']; $authpassword = $user->getauthpassword(); return md5($plain . $authpassword['salt']) == $authpassword['password']; } }
3. 将user providers换成我们自己的gfzxeloquentuserprovider
修改 app/providers/authserviceprovider.php
<?php namespace app\providers; use app\foundation\auth\gfzxeloquentuserprovider; use auth; use illuminate\support\facades\gate; use illuminate\foundation\support\providers\authserviceprovider as serviceprovider; class authserviceprovider extends serviceprovider { . . . /** * register any authentication / authorization services. * * @return void */ public function boot() { $this->registerpolicies(); auth::provider('gfzx-eloquent', function ($app, $config) { return new gfzxeloquentuserprovider($this->app['hash'], $config['model']); }); } }
4. 修改 config/auth.php
'providers' => [ 'users' => [ 'driver' => 'gfzx-eloquent', 'model' => app\models\user::class, ], ],
这是就可以用过salt+passwrod的方式密码认证了
文章参考
到此这篇关于laravel修改用户模块的密码验证实现的文章就介绍到这了,更多相关laravel修改用户模块的密码验证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: javaScript操作符