laravel 5.0如何实现登录密码字段不为password或加签方式自定义。

水到渠成
  • 122

前前后后花了很长时间终于彻底明白了laravel5.0是如何实现登录的,感觉非常复杂。

比如说现在数据库中密码字段为pwd,而不是系统默认的password时,修改的文件有:

// \vendor\laravel\framework\src\Illuminate\Auth\Authenticatable.php
public function getAuthPassword()
{
//    return $this->password; 修改为
    return $this->pwd;
}

如果加签方式不一样,修改的文件有:

// \vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php
public function validateCredentials(UserContract $user, array $credentials)
{
    $plain = $credentials['password'];

    // 下面的$this->hasher->check修改为自定义加签后的字符串相等判断
    return $this->hasher->check($plain, $user->getAuthPassword());
}

这样修改的话相当于修改了laravel的源码,一点也不优雅,不知有没有什么更好的办法?

回复
阅读 4.2k
3 个回答

不知道为什么忽略我的答案

更优雅的方法当然是实现自己的IlluminateContractsHashingHasher,然后注入到EloquentUserProvider里啊。

你说的明文密码,其实就是在make方法中,让返回值直接返回明文;在check中直接对比明文数据就好了

interface Hasher
{
    /**
     * Hash the given value.
     *
     * @param  string  $value
     * @param  array   $options
     * @return string
     */
    public function make($value, array $options = []);
 
    /**
     * Check the given plain value against a hash.
     *
     * @param  string  $value
     * @param  string  $hashedValue
     * @param  array   $options
     * @return bool
     */
    public function check($value, $hashedValue, array $options = []);
 
    /**
     * Check if the given hash has been hashed using the given options.
     *
     * @param  string  $hashedValue
     * @param  array   $options
     * @return bool
     */
    public function needsRehash($hashedValue, array $options = []);
}

实现之后在appProvidersAuthServiceProvider.php里写

public function boot()
{
    $this->registerPolicies();

    //使用authme的Hash来处理密码
    Auth::provider('authme', function($app, array $config) {
        return new EloquentUserProvider(new AuthmeHasher,$config['model']);
    });
}

当然,最后别忘了设置configauth.php下面的providers中driver为你上面在Auth::provider中声明的名字

/*
    |--------------------------------------------------------------------------
    | 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' => 'authme',
            'model' => App\User::class,
        ],
 
        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

具体的例子可以看https://www.onlyke.com/html/8...

你也可以自己实现登陆注册啊。不过我觉得自带的已经很好用了。
如果你往user表加字段了获取字段值的话,可以 auth()->user()->你的字段名

你知道吗?

宣传栏