在实际项目开发中,用户身份验证是核心功能之一。若因业务需求必须使用除默认 users 表以外的数据表来存储用户信息并进行认证,则需要额外配置以完成该功能。
假设当前场景仅需替换登录用户的来源表,且新表的名称及结构与框架默认的 users 表不同。虽然官方文档未直接提供此类场景的操作指南,但通过分析框架底层的认证源码,可以轻松实现这一目标。
首先,我们需要定义一张用于登录的自定义表,其结构及模拟数据示例如下:
表 admins
| id | login_name | login_pass |
|---|---|---|
| 1 | admin | 2y10$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,
],
],
];
系统默认启用的守卫(guard)为 web,其使用的认证驱动为 session,而对应的用户提供器(provider)为 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 表进行用户登录。
在 Laravel 5.4 中,默认的 Auth 登录机制会将邮件地址和用户密码传递给 attempt 方法进行认证。系统通过 email 值查找用户,若找到用户,则将数据库中哈希存储的 password 字段与传递过来的经哈希处理的 password 值进行比较。若两者匹配,则为该用户开启认证 Session。
基于上述分析,若需支持如 salt+password 等自定义密码认证方式,则需要对 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+password 的方式实现密码认证。
文章参考
laravel 修改用户模块密码验证
Laravel 中自定义用户登录的数据表
到此这篇关于laravel修改用户模块的密码验证实现的文章就介绍到这了,更多相关laravel修改用户模块的密码验证内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!