当前位置:首页 > PHP教程 > PHP常见问题

通过修改LaravelAuth使用salt和password进行认证用户详解

前言

本文主要给大家介绍了通过修改laravel auth用salt和password进行认证用户的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍:

laraval自带的用户认证系统auth非常强大易用,不过在laravel的用户认证系统中用户注册、登录、找回密码这些模块中用到密码加密和认证算法时使用的都是bcrypt,而很多之前做的项目用户表里都是采用存储salt + password加密字符串的方式来记录用户的密码的,这就给使用laravel框架来重构之前的项目带来了很大的阻力,不过最近自己通过在网上找资料、看社区论坛、看源码等方式完成了对laravel auth的修改,在这里分享出来希望能对其他人有所帮助。 开篇之前需要再说明下如果是新项目应用laravel框架,那么不需要对auth进行任何修改,默认的bcrypt加密算法是比salt + password更安全更高效的加密算法。

修改用户注册

首先,在laravel 里启用验证是用的artisan命令

php artisan make:auth

执行完命令后在routes文件(位置:app/http/routes.php)会多一条静态方法调用

route::auth();

这个route是laravel的一个facade (位于illuminatesupportfacadesroute), 调用的auth方法定义在illuminateroutingrouter类里, 如下可以看到auth方法里就是定义了一些auth相关的路由规则

/** * register the typical authentication routes for an application. * * @return void */ public function auth() { // authentication routes... $this->get('login', 'authauthcontroller@showloginform'); $this->post('login', 'authauthcontroller@login'); $this->get('logout', 'authauthcontroller@logout'); // registration routes... $this->get('register', 'authauthcontroller@showregistrationform'); $this->post('register', 'authauthcontroller@register'); // password reset routes... $this->get('password/reset/{token?}', 'authpasswordcontroller@showresetform'); $this->post('password/email', 'authpasswordcontroller@sendresetlinkemail'); $this->post('password/reset', 'authpasswordcontroller@reset'); }

通过路由规则可以看到注册时请求的控制器方法是authcontroller的register方法, 该方法定义在illuminatefoundationauthregistersusers这个traits里,authcontroller在类定义里引入了这个traits.

/** * handle a registration request for the application. * * @param illuminatehttprequest $request * @return illuminatehttpresponse */ public function register(request $request) { $validator = $this->validator($request->all()); if ($validator->fails()) { $this->throwvalidationexception( $request, $validator ); } auth::guard($this->getguard())->login($this->create($request->all())); return redirect($this->redirectpath()); }

在register方法里首先会对request里的用户输入数据进行验证,你只需要在authcontroller的validator方法里定义自己的每个输入字段的验证规则就可以

protected function validator(array $data) { return validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255|unique:user', 'password' => 'required|size:40|confirmed', ]); }

接着往下看验证通过后,laravel会掉用authcontroller的create方法来生成新用户,然后拿着新用户的数据去登录auth::guard($this->getguard())->login($this->create($request->all()));

所以我们要自定义用户注册时生成用户密码的加密方式只需要修改authcontroller的create方法即可。

比如:

/** * create a new user instance after a valid registration. * * @param array $data * @return user */ protected function create(array $data) { $salt = str::random(6); return user::create([ 'nickname' => $data['name'], 'email' => $data['email'], 'password' => sha1($salt . $data['password']), 'register_time' => time(), 'register_ip' => ip2long(request()->ip()), 'salt' => $salt ]); }

修改用户登录

修改登录前我们需要先通过路由规则看一下登录请求的具体控制器和方法,在上文提到的auth方法定义里可以看到

$this->get('login', 'authauthcontroller@showloginform'); $this->post('login', 'authauthcontroller@login'); $this->get('logout', 'authauthcontroller@logout');

验证登录的操作是在apphttpcontrollersauthauthcontroller类的login方法里。打开authcontroller发现auth相关的方法都是通过性状(traits)引入到类内的,在类内use 要引入的traits,在编译时php就会把traits里的代码copy到类中,这是php5.5引入的特性具体适用场景和用途这里不细讲。 所以authcontroller@login方法实际是定义在
illuminatefoundationauthauthenticatesusers这个traits里的

/** * handle a login request to the application. * * @param illuminatehttprequest $request * @return illuminatehttpresponse */ public function login(request $request) { $this->validatelogin($request); $throttles = $this->isusingthrottlesloginstrait(); if ($throttles && $lockedout = $this->hastoomanyloginattempts($request)) { $this->firelockoutevent($request); return $this->sendlockoutresponse($request); } $credentials = $this->getcredentials($request); if (auth::guard($this->getguard())->attempt($credentials, $request->has('remember'))) { return $this->handleuserwasauthenticated($request, $throttles); } if ($throttles && ! $lockedout) { $this->incrementloginattempts($request); } return $this->sendfailedloginresponse($request); }

登录验证的主要操作是在auth::guard($this->getguard())->attempt($credentials, $request->has('remember'));这个方法调用中来进行的,auth::guard($this->getguard()) 获取到的是illuminateauthsessionguard (具体如何获取的看auth这个facade illuminateauthauthmanager里的源码)

看一下sessionguard里attempt 方法是如何实现的:

public function attempt(array $credentials = [], $remember = false, $login = true) { $this->fireattemptevent($credentials, $remember, $login); $this->lastattempted = $user = $this->provider->retrievebycredentials($credentials); if ($this->hasvalidcredentials($user, $credentials)) { if ($login) { $this->login($user, $remember); } return true; } if ($login) { $this->firefailedevent($user, $credentials); } return false; } /** * 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); }

retrievebycredentials是用传递进来的字段从数据库中取出用户数据的,validatecredentials是用来验证密码是否正确的实际过程。

这里需要注意的是$this->provider这个provider是一个实现了illuminatecontractsauthuserprovider类的provider, 我们看到目录illuminateauth下面有两个userprovider的实现,分别为databaseuserprovider和eloquentuserprovider, 但是我们验证密码的时候是通过那个来验证的呢,看一下auth的配置文件

'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => appuser::class, //这个是driver用的model ], ],

这里配置的是driver => eloquent , 那么就是通过eloquentuserprovider的retrievebycredentials来验证的, 这个eloquentuserprovider 是在sessionguard实例化时被注入进来的, (具体是怎么通过读取auth配置文件, 实例化相应的provider注入到sessionguard里的请查阅illuminateauthauthmanager 里createsessiondriver方法的源代码)

接下来我们继续查看eloquentuserprovider中retrievebycredentials和validatecredentials方法的实现:

/** * retrieve a user by the given credentials. * * @param array $credentials * @return illuminatecontractsauthauthenticatable|null */ public function retrievebycredentials(array $credentials) { if (empty($credentials)) { return; } $query = $this->createmodel()->newquery(); foreach ($credentials as $key => $value) { if (! str::contains($key, 'password')) { $query->where($key, $value); } } return $query->first(); } /** * validate a user against the given credentials. * * @param illuminatecontractsauthauthenticatable $user * @param array $credentials * @return bool */ public function validatecredentials(usercontract $user, array $credentials) { $plain = $credentials['password']; return $this->hasher->check($plain, $user->getauthpassword()); }

上面两个方法retrievebycredentials用除了密码以外的字段从数据库用户表里取出用户记录,比如用email查询出用户记录,然后validatecredentials方法就是通过$this->haser->check来将输入的密码和哈希的密码进行比较来验证密码是否正确。

好了, 看到这里就很明显了, 我们需要改成自己的密码验证就是自己实现一下validatecredentials就可以了, 修改$this->hasher->check为我们自己的密码验证规则就可以了。

首先我们修改$user->getauthpassword()把数据库中用户表的salt和password传递到validatecredentials中
修改appuser.php 添加如下代码

/** * the table associated to this model */ protected $table = 'user';//用户表名不是laravel约定的这里要指定一下
/** * 禁用laravel自动管理timestamp列 */ public $timestamps = false; /** * 覆盖laravel中默认的getauthpassword方法, 返回用户的password和salt字段 * @return type */ public function getauthpassword() { return ['password' => $this->attributes['password'], 'salt' => $this->attributes['salt']]; }

然后我们在建立一个自己的userprovider接口的实现,放到自定义的目录中:

新建app/foundation/auth/admineloquentuserprovider.php

namespace appfoundationauth; use illuminateautheloquentuserprovider; use illuminatecontractsauthauthenticatable; use illuminatesupportstr; class admineloquentuserprovider extends eloquentuserprovider { /** * validate a user against the given credentials. * * @param illuminatecontractsauthauthenticatable $user * @param array $credentials */ public function validatecredentials(authenticatable $user, array $credentials) { $plain = $credentials['password']; $authpassword = $user->getauthpassword(); return sha1($authpassword['salt'] . $plain) == $authpassword['password']; } }

最后我们修改auth配置文件让laravel在做auth验证时使用我们刚定义的provider,
修改config/auth.php:

'providers' => [ 'users' => [ 'driver' => 'admin-eloquent', 'model' => appuser::class, ] ]

修改app/provider/authserviceprovider.php

public function boot(gatecontract $gate) { $this->registerpolicies($gate); auth::provider('admin-eloquent', function ($app, $config) { return new appfoundationauthadmineloquentuserprovider($app['hash'], $config['model']); }); }

auth::provider方法是用来注册provider构造器的,这个构造器是一个closure,provider方法的具体代码实现在authmanager文件里

public function provider($name, closure $callback) { $this->customprovidercreators[$name] = $callback; return $this; }

闭包返回了admineloquentuserprovider对象供laravel auth使用,好了做完这些修改后laravel的auth在做用户登录验证的时候采用的就是自定义的salt + password的方式了。

修改重置密码

laravel 的重置密码的工作流程是:

  • 向需要重置密码的用户的邮箱发送一封带有重置密码链接的邮件,链接中会包含用户的email地址和token。
  • 用户点击邮件中的链接在重置密码页面输入新的密码,laravel通过验证email和token确认用户就是发起重置密码请求的用户后将新密码更新到用户在数据表的记录里。

第一步需要配置laravel的email功能,此外还需要在数据库中创建一个新表password_resets来存储用户的email和对应的token

create table `password_resets` ( `email` varchar(255) collate utf8_unicode_ci not null, `token` varchar(255) collate utf8_unicode_ci not null, `created_at` timestamp not null, key `password_resets_email_index` (`email`), key `password_resets_token_index` (`token`) ) engine=innodb default charset=utf8 collate=utf8_unicode_ci;

通过重置密码表单的提交地址可以看到,表单把新的密码用post提交给了/password/reset,我们先来看一下auth相关的路由,确定/password/reset对应的控制器方法。

$this->post('password/reset', 'authpasswordcontroller@reset');

可以看到对应的控制器方法是apphttpcontrollersauthpasswordcontroller类的reset方法,这个方法实际是定义在illuminatefoundationauthresetspasswords 这个traits里,passwordcontroller引入了这个traits

/** * reset the given user's password. * * @param illuminatehttprequest $request * @return illuminatehttpresponse */ public function reset(request $request) { $this->validate( $request, $this->getresetvalidationrules(), $this->getresetvalidationmessages(), $this->getresetvalidationcustomattributes() ); $credentials = $this->getresetcredentials($request); $broker = $this->getbroker(); $response = password::broker($broker)->reset($credentials, function ($user, $password) { $this->resetpassword($user, $password); }); switch ($response) { case password::password_reset: return $this->getresetsuccessresponse($response); default: return $this->getresetfailureresponse($request, $response); } }

方法开头先通过validator对输入进行验证,接下来在程序里传递把新密码和一个闭包对象传递给password::broker($broker)->reset();方法,这个方法定义在illuminateauthpasswordspasswordbroker类里.

/** * reset the password for the given token. * * @param array $credentials * @param closure $callback * @return mixed */ public function reset(array $credentials, closure $callback) { // if the responses from the validate method is not a user instance, we will // assume that it is a redirect and simply return it from this method and // the user is properly redirected having an error message on the post. $user = $this->validatereset($credentials); if (! $user instanceof canresetpasswordcontract) { return $user; } $pass = $credentials['password']; // once we have called this callback, we will remove this token row from the // table and return the response from this callback so the user gets sent // to the destination given by the developers from the callback return. call_user_func($callback, $user, $pass); $this->tokens->delete($credentials['token']); return static::password_reset; }

在passwordbroker的reset方法里,程序会先对用户提交的数据做再一次的认证,然后把密码和用户实例传递给传递进来的闭包,在闭包调用里完成了将新密码更新到用户表的操作, 在闭包里程序调用了的passwrodcontroller类的resetpassword方法

function ($user, $password) { $this->resetpassword($user, $password); });

passwrodcontroller类resetpassword方法的定义

protected function resetpassword($user, $password) { $user->forcefill([ 'password' => bcrypt($password), 'remember_token' => str::random(60), ])->save(); auth::guard($this->getguard())->login($user); }

在这个方法里laravel 用的是bcrypt 加密了密码, 那么要改成我们需要的salt + password的方式,我们在passwordcontroller类里重写resetpassword方法覆盖掉traits里的该方法就可以了。

/** * 覆盖resetspasswords traits里的resetpassword方法,改为用sha1(salt + password)的加密方式 * reset the given user's password. * * @param illuminatecontractsauthcanresetpassword $user * @param string $password * @return void */ protected function resetpassword($user, $password) { $salt = str::random(6); $user->forcefill([ 'password' => sha1($salt . $password), 'salt' => $salt, 'remember_token' => str::random(60), ])->save(); auth::guard($this->getguard())->login($user); }

结语

到这里对laravel auth的自定义就完成了,注册、登录和重置密码都改成了sha1(salt + password)的密码加密方式, 所有自定义代码都是通过定义laravel相关类的子类和重写方法来完成没有修改laravel的源码,这样既保持了良好的可扩展性也保证了项目能够自由迁移。

注:使用的laravel版本为5.2

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对硕编程的支持。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐