Laravel 的 Auth::attempt () 初探及修改 bcrypt 验证为 MD5

如果你在使用Laravel的话,用户的代码只需要一行代码就可以搞定

if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
    // 验证成功的逻辑
}

但是,如果你想切换为自定义的加密验证方式,那么这篇文章可能会给你一些思路
比如,如果我想把密码的验证方式更换为MD5,我应该怎么做呢?
别急,先从laravel框架的验证流程开始
我们调用的Auth::attempt()在哪里实现的呢?
先从Auth找起
config/app.php

'aliases' => [

        'App' => Illuminate\Support\Facades\App::class,
        'Artisan' => Illuminate\Support\Facades\Artisan::class,
        'Auth' => Illuminate\Support\Facades\Auth::class,
                // ...
        ]

我们看到我们调用Auth其实是调用了

 Illuminate\Support\Facades\Auth::class

打开这个类文件

 class Auth extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'auth';
    }
    // ...
}

可以看到,Auth是通过Facade动态绑定的,绑定到哪里呢,进一步寻找我们发现
在 vendor/laravel/framework/src/Illuminate/AuthServiceProvider

 class AuthServiceProvider extends ServiceProvider
{
    /**
     * Register the authenticator services.
     *
     * @return void
     */
    protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function ($app) {
            $app['auth.loaded'] = true;
            return new AuthManager($app);
        });

        $this->app->singleton('auth.driver', function ($app) {
            return $app['auth']->guard();
        });
    }
}

默认的Auth绑定了AuthManager,打开AuthManager文件

 <?php
namespace Illuminate\Auth;

use Closure;
use InvalidArgumentException;
use Illuminate\Contracts\Auth\Factory as FactoryContract;
class AuthManager implements FactoryContract
{
    use CreatesUserProviders;

    protected $app;

    protected $guards = [];

    public function guard($name = null)
    {
        $name = $name ?: $this->getDefaultDriver();

        return isset($this->guards[$name])
                    ? $this->guards[$name]
                    : $this->guards[$name] = $this->resolve($name);
    }

    public function getDefaultDriver()
    {
        return $this->app['config']['auth.defaults.guard'];
    }

    public function __call($method, $parameters)
    {

        return $this->guard()->{$method}(...$parameters);
    }
}

并没有找到attempt方法,不过有一个__call的魔术方法,那肯定是他里面没错了,为了快速找到他究竟是何方神圣,直接用

 dd(get_class($this->guard()));

真正的attempt究竟被谁调用了呢?
打印了SessionGuard,继续找下去

Illuminate\Auth\SessionGuard

打开该类,发现终于发现了我们寻找好久的attempt的实现

class SessionGuard implements StatefulGuard, SupportsBasicAuth
{
    use GuardHelpers, Macroable;
    public function attempt(array $credentials = [], $remember = false)
    {
        $this->fireAttemptEvent($credentials, $remember);

        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
        if ($this->hasValidCredentials($user, $credentials)) {
            $this->login($user, $remember);

            return true;
        }
        $this->fireFailedEvent($user, $credentials);

        return false;
    }

这就是我们一直使用的attempt的实现,通过 $this->provider->retrieveByCredentials($credentials)获取用户信息,并验证,如果成功则登录,并返回true
所以我们真正做的密码验证肯定在retrieveByCredentials这个方法里面
Laravel 默认提供了 UserProvider 为 EloquentUserProvider
打开改方法

class EloquentUserProvider implements UserProvider
{
    protected $hasher;

    protected $model;
    public function __construct(HasherContract $hasher, $model)
    {
        $this->model = $model;
        $this->hasher = $hasher;
    }
    public function validateCredentials(UserContract $user, array $credentials)
    {

        $plain = $credentials['password'];
        return $this->hasher->check($plain, $user->getAuthPassword());
    }
    public function setHasher(HasherContract $hasher)
    {
        $this->hasher = $hasher;

        return $this;
    }
}

所以这里的hasher就是系统默认的BcryptHasher了,我们修改他直接注入自己的haser
ok,了解思路了,开始搞它

1.编写自己的hasher

<?php

namespace App\Helpers\Hasher;

use Illuminate\Contracts\Hashing\Hasher;

class MD5Hasher implements Hasher
{
    public function check($value, $hashedValue, array $options = [])
    {

        return $this->make($value) === $hashedValue;
    }

    public function needsRehash($hashedValue, array $options = [])
    {
        return false;
    }

    public function make($value, array $options = [])
    {
        $value = env('SALT', '').$value;

        return md5($value);  //这里写你自定义的加密方法
    }

}

2.用自己的Hasher替换默认的Hasher

创建MD5HashServiceProvider

php artisan make:provider MD5HashServiceProvider

添加如下方法

<?php

namespace App\Providers;

use App\Helpers\Hasher\MD5Hasher;
use Illuminate\Support\ServiceProvider;

class MD5HashServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->app->singleton('hash', function () {
            return new MD5Hasher;
        });
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function provides()
    {
        return ['hash'];
    }
}

然后在config/app.phpproviders中,将

Illuminate\Hashing\HashServiceProvider::class,

替换为

\App\Providers\MD5HashServiceProvider::class,

OK,大功告成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值