laravel修改用户模块的密码验证实现

目录
  • 从配置文件入手
  • 使用Auth门面的attempt方法进行登录
  • 修改 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,
            ],
        ],

    ];

默认使用的守卫是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 中自定义用户登录的数据表

到此这篇关于laravel修改用户模块的密码验证实现的文章就介绍到这了,更多相关laravel修改用户模块的密码验证内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • laravel unique验证、确认密码confirmed验证以及密码修改验证的方法

    confirmed 验证字段必须有一个匹配字段 foo_confirmation,例如,如果验证字段是 password,必须输入一个与之匹配的 password_confirmation 字段. same:field 给定字段和验证字段必须匹配 protected $fillable = ['name', 'password']; public static $rules = [ 'name' => 'required|unique:managers', 'password' => 'req

  • laravel修改用户模块的密码验证实现

    目录 从配置文件入手 使用Auth门面的attempt方法进行登录 修改 Admin 模型 文章参考 做项目的时候,用户认证几乎是必不可少的,如果我们的项目由于一些原因不得不使用 users 之外的用户表进行认证,那么就需要多做一点工作来完成这个功能. 现在假设我们只需要修改登录用户的表,表名和表结构都与框架默认的表users不同,文档没有教我们如何去做,但是别慌,稍微看下框架实现用户认证的源码就能轻松实现. 首先,自定义一张表用来登录,表结构和模拟数据如下: 表 admins id login

  • mysql5.7 修改用户初始密码的方法

    当用户首次安装MySQL数据库时,总是想修改root的初始化密码,我也是,每次都百度一下,下面主要给出一些操作数据库的常用SQL和一些基本概念性的东西. 修改用户的初始化密码: SET PASSWORD = PASSWORD('your new password'); ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER; flush privileges; 创建新的用户: CREATE USER 'username'@'host' IDENTI

  • laravel的用户修改密码与绑定邮箱的详细操作

    目录 一.修改密码 1.1 创建修改密码控制器 1.2 创建修改密码路由 1.3 测试效果 二.绑定邮箱 2.1 绑定邮箱控制器 2.2 创建对应路由 2.3 创建发送邮件的类 2.4 测试效果 一.修改密码 1.1 创建修改密码控制器 运行命令php artisan make:controller Auth/PasswordController 写入修改密码方法: /** * 修改密码 */ public function updatePassword(Request $request) {

  • linux下passwd命令设置修改用户密码的方法

    1.passwd 简单说明: 我们已经学会如何添加用户了,所以我们还要学习设置或修改用户的密码:passwd命令的用法也很多,我们只选如下的几个参数加以说明:想了解更多,请参考man passwd或passwd --help : passwd [OPTION...] passwd 作为普通用户和超级权限用户都可以运行,但作为普通用户只能更改自己的用户密码,但前提是没有被root用户锁定:如果root用户运行passwd ,可以设置或修改任何用户的密码: passwd 命令后面不接任何参数或用户名

  • mysql修改用户密码报错的解决方法

    目录 mysql修改密码报错 解决办法: 关于 mysql 密码策略相关参数: 关于 validate_password_policy 的取值: mysql修改密码报错 Your password does not satisfy the current policy requirements 这是 mysql 初始化时,使用临时密码,修改自定义密码时,由于自定义密码比较简单,就出现了不符合密码策略的问题. 密码策略问题异常信息: ERROR 1819 (HY000): Your passwor

  • Linux下交互式与非交互式修改用户密码的例子

    最近管理的一批机器,有个需求是要统一修改一个帐号的用户名密码,比如将qa帐号的密码改为1234,后来还为了脚本化,很方便的执行,还使用了非交互式地修改用户的密码.简单记录一下吧. 1. 交互式配置本地用户的密码:passwd 命令 复制代码 代码如下: [root@host_221-81 ~]# passwd qa Changing password for user qa. New password: BAD PASSWORD: it is too short BAD PASSWORD: is

  • Laravel框架用户登陆身份验证实现方法详解

    本文实例讲述了Laravel框架用户登陆身份验证实现方法.分享给大家供大家参考,具体如下: laravel中检测用户是否登录,有以下的代码: if ( !Auth::guest() ) { return Redirect::to('/dashboard'); } 那Auth::guest是如何调用的呢? laravel用了Facade模式,相关门面类在laravel/framework/src/Illuminate/Support/Facades文件夹定义的,看下Auth类的定义: class

  • Laravel修改验证提示信息为中文的示例

    1.覆盖提示信息: 打开resource/lang/en/validation.php注释掉英文提示信息 将下面的提示信息覆盖英文提示信息 <?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |---------------------------------------------------------

  • Laravel 修改验证异常的响应格式实例代码详解

    Laravel 默认验证不通过后响应格式如下,有时此格式并不满足自己要求,需要修改格式. // status 422 { "message":"The given data was invalid.", "errors":{ "url":[ "url 无效的格式" ] } } 当 Request 验证失败时会抛出 ValidationException异常,最终交由全局异常Handler类处理.Handle

  • laravel 实现用户登录注销并限制功能

    1. 创建登录控制器 在项目根目录输入: php artisan make:controller Admin/LoginController 2.创建用户模块 以及数据库 php artisan make:model Model/Admin -m 运行之后 项目中会新增两个PHP文件 新创建了admins用户表,此用户表默认新建中只有主键,创建时间,编辑时间.我们接下来新加两个字段 用户名(username) 和密码(password). 在up函数中加上这两个字段,后面可以按自己的需求添加属性

随机推荐