Laravel Auth 自定义 Salt+Password 认证方案详解
前言
本文将深入探讨如何调整 Laravel 的 Auth 组件,使其支持基于 salt 和 password 组合的用户认证机制,供开发者参考实践。
Laravel 内置的 Auth 系统功能完善且易于集成,但在处理用户注册、登录及找回密码等流程时,默认采用 bcrypt 算法进行密码哈希。然而,许多遗留项目的数据库中存储的是 salt 拼接 password 后的加密字符串。这导致在使用 Laravel 重构旧系统时面临兼容性难题。经过查阅官方文档、社区讨论及源码分析,作者成功实现了 Auth 模块的定制化改造,现分享此方案以助他人解决类似痛点。需强调的是,对于全新 Laravel 项目,建议直接使用默认的 bcrypt 算法,其在安全性与性能上均优于传统的 salt + password 方案。
修改用户注册
在 Laravel 项目中启用基础身份验证功能,需执行 artisan 命令:
php artisan make:auth
执行该命令后,路由文件(通常位于 app/Http/routes.php)中会自动添加一条静态路由调用。
Route::auth();
上述 Route 是 Laravel 的一个 Facade(位于 Illuminate\Support\Facades\Route),其调用的 auth 方法定义在 Illuminate\Routing\Router 类中。该方法内部定义了若干与 Auth 相关的路由规则。
/**
* Register the typical authentication routes for an application.
*
* @return void
*/
public function auth()
{
// Authentication Routes...
$this->get('login', 'Auth\AuthController@showLoginForm');
$this->post('login', 'Auth\AuthController@login');
$this->get('logout', 'Auth\AuthController@logout');
// Registration Routes...
$this->get('register', 'Auth\AuthController@showRegistrationForm');
$this->post('register', 'Auth\AuthController@register');
// Password Reset Routes...
$this->get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
$this->post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
$this->post('password/reset', 'Auth\PasswordController@reset');
}
根据路由规则可知,注册请求对应的控制器方法是 AuthController 的 register 方法。该方法实际定义在 \Illuminate\Foundation\Auth\RegistersUsers Trait 中,而 AuthController 在类定义中引入了此 Trait。
/**
* Handle a registration request for the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
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 方法中,首先会对请求中的用户输入数据进行验证。开发者只需在 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', 'Auth\AuthController@showLoginForm');
$this->post('login', 'Auth\AuthController@login');
$this->get('logout', 'Auth\AuthController@logout');
登录验证的核心逻辑位于 \App\Http\Controllers\Auth\AuthController 类的 login 方法中。观察 AuthController 源码可知,其相关功能均通过 Traits 引入。PHP 5.5 引入的 Traits 特性允许在编译时将代码复制到类中,具体细节此处不赘述。以AuthController@login 方法实际上定义在 \Illuminate\Foundation\Auth\AuthenticatesUsers Trait 中。
/**
* Handle a login request to the application.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
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()) 获取到的是 \Illuminate\Auth\SessionGuard 实例(具体获取机制可参考 Auth Facade \Illuminate\Auth\AuthManager 的源码)。
接下来查看 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 必须实现 \Illuminate\Contracts\Auth\UserProvider 接口。在 Illuminate\Auth 目录下存在两个实现类:DatabaseUserProvider 和 EloquentUserProvider。具体使用哪一个进行密码验证,需查看 auth 配置文件。
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class, //这个是driver用的Model
],
],
配置文件中指定了 driver => eloquent,这意味着将通过 EloquentUserProvider 的 retrieveByCredentials 进行验证。该 Provider 在 SessionGuard 实例化时被注入(具体通过读取 config/auth.php 并调用 \Illuminate\Auth\AuthManager 的 createSessionDriver 方法实现)。
继续查看 EloquentUserProvider 中 retrieveByCredentials 和 validateCredentials 的实现:
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $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 替换为符合 salt + password 逻辑的验证规则即可。
首先,我们需要修改 $user->getAuthPassword(),以便将数据库中的 salt 和 password 传递给 validateCredentials。需在 App\User.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 App\Foundation\Auth;
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Str;
class AdminEloquentUserProvider extends EloquentUserProvider
{
/**
* Validate a user against the given credentials.
*
* @param \Illuminate\Contracts\Auth\Authenticatable $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' => App\User::class,
]
]
同时修改 app/Provider/AuthServiceProvider.php
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
\Auth::provider('admin-eloquent', function ($app, $config) {
return New \App\Foundation\Auth\AdminEloquentUserProvider($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 的邮件功能,并在数据库中创建 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', 'Auth\PasswordController@reset');
对应控制器方法为 \App\Http\Controllers\Auth\PasswordController 类的 reset 方法。该方法实际定义在 \Illuminate\Foundation\Auth\ResetsPasswords Trait 中,PasswordController 引入了此 Trait。
/**
* Reset the given user's password.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
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() 方法,该方法定义在 \Illuminate\Auth\Passwords\PasswordBroker 类中。
/**
* 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 方法中,程序再次对用户提交数据进行认证,然后将密码和用户实例传递给传入的闭包。在闭包调用中完成新密码更新操作,此时调用了 PasswordController 类的 resetPassword 方法。
function ($user, $password) {
$this->resetPassword($user, $password);
});
PasswordController 类 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 方法,覆盖 Trait 中的同名方法即可。
/**
* 覆盖ResetsPasswords traits里的resetPassword方法,改为用sha1(salt + password)的加密方式
* Reset the given user's password.
*
* @param \Illuminate\Contracts\Auth\CanResetPassword $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 版本为 5.2
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对本站的支持。