当前位置: 首页 > 编程文章 >

Laravel自定义用户表认证:修改密码验证逻辑

Laravel自定义用户表认证:修改密码验证逻辑

作者:陆宁时间:2026-09-07 13:01:04浏览:110

在Laravel项目中,若需使用非默认的users表进行用户认证,需调整配置并处理密码验证逻辑。默认情况下,validateCredentials方法要求密码字段名为password且不可自定义。通过重写EloquentUserProvider的validateCredentials方法或修改模型getAuthPassword方法,可实现如salt+password等自定义认证方式,确保Admin模型正确继承接口并返回正确的加密密码字段。

本文目录展开

在实际项目开发中,用户身份验证是核心功能之一。若因业务需求必须使用除默认 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修改用户模块的密码验证内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

上一篇
PHP中fopen与file_get_contents读取文件及URL的区别

在PHP开发中,fopen和file_get_contents是常用的文件读取函数。两者虽无本质区别,但使用方式不同:fopen需配合fgets和fclose处理资源流,适合大文件或逐行读取;file_get_contents一次性加载内容为字符串,代码更简洁,但大文件易占用内存。本文通过实例解析二者在本地文件及URL访问中的具体用法、返回值差异及注意事项。

下一篇
PHP数组操作实例分析:添加、删除、排序与查找

PHP数组是开发中的核心数据结构,掌握其基本操作至关重要。本文通过实例演示了数组的添加、删除、计算、反转、排序及查找等常用功能,帮助开发者快速理解并应用这些基础API,提升代码编写效率。

相关文章

更多
Laravel Validator 自定义验证与中间件集成方案

在 Laravel Web 开发中,常规 Validator 或 Request 类在处理自定义提示信息及规则时存在局限。通过构建抽象验证基类、定制 HTTP 中间件并结合路由配置,可实现统一的参数校验流程。该方案允许集中管理验证逻辑,简化控制器代码,提升参数处理的规范性与复用性。

2025.06.09 1,003
Laravel Valet:Mac上极简的PHP本地开发环境搭建教程

使用 Homebrew 安装 valet ,运行 valet install 配置 Nginx 和 DnsMasq ,进入项目目录执行 valet park 即可通过 .test 后缀访问。

2025.01.10 1,003
Laravel统一API错误码与JSON响应格式方案

针对Laravel框架在Web API开发中返回HTML页面代码及JSON结构不统一的问题,本文提出两种解决方案。首先通过自定义Middleware强制设置Accept头以拦截非JSON请求;其次基于PHP魔术方法模拟枚举特性,结合全局异常处理器实现统一的JSON响应结构(code、msg、data),确保前后端交互的规范性。

2026.05.24 991
新手入门PHP开发,推荐从哪个框架开始学习?

新手入门 PHP 开发,推荐从 Laravel 开始学习。它拥有完善的文档、活跃的社区和现代化的语法结构,能帮助你快速建立正确的开发习惯。

2025.06.03 980
Laravel 软删除左连接查询报错及 setTable 解决方案

在 Laravel 中使用模型进行左连接查询并设置表别名时,若模型启用了软删除功能,执行查询会抛出 "Column not found: Unknown column" 错误。这是因为软删除作用域生成的条件使用了模型原始的全限定表名,而非 SQL 中的别名。通过在查询构建器中调用 setTable 方法指定表名为别名,即可解决该冲突。

2026.08.08 978
Laravel 服务容器如何解析依赖

Laravel 服务容器负责为对象提供所需依赖,并可按配置决定接口对应的实现。测试时可以替换绑定,验证调用者能否在不修改业务逻辑的情况下使用另一实现,从而区分依赖解析和对象内部的问题。

2025.06.16 976

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。