Laravel不修改源碼的前提Auth驗證替換成md5

在讀這篇文章之前,請先弄明白容器的運作原理。
注意,版本是5.1 LTS那個。其他版本的原理都差不多。

我們在換成laravel的時候,可能會遇到一個問題,就是以前可能用md5或者其他驗證方式的,然后在laravel里面,密碼的認證方式又換了,不想自己重寫認證方式,又想沿用以前的md5需求。

其實我們在看laravel的Auth::attempt()的時候,可以發現,laravel,調用的驗證方法是基于一個hash類。

    /**
     * Validate a user against the given credentials.
     *
     * @param \Illuminate\Contracts\Auth\Authenticatable $user
     * @param array                                      $credentials
     *
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }

我們只要替換了這個hash類,就完全可以做到使用我們想要的驗證方式去驗證登錄了。
那么怎么替換呢?我們其實可以發現,在config/auth.php里面,我們設置了auth的驅動,這個驅動一般默認是eloquent,在vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php里面。

    /**
     * Register the authenticator services.
     *
     * @return void
     */
    protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function ($app) {
            // Once the authentication service has actually been requested by the developer
            // we will set a variable in the application indicating such. This helps us
            // know that we need to set any queued cookies in the after event later.
            $app['auth.loaded'] = true;

            return new AuthManager($app);
        });

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

這里面根據配置綁定了hash的驅動,那么我們接下來就看一下綁定了什么驅動,到目錄vendor/laravel/framework/src/Illuminate/Auth下,我們可以看到有EloquentUserProvider.php

<?php
namespace Illuminate\Auth;

use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;

class EloquentUserProvider implements UserProvider
{
    /**
     * The hasher implementation.
     *
     * @var \Illuminate\Contracts\Hashing\Hasher
     */
    protected $hasher;

    /**
     * The Eloquent user model.
     *
     * @var string
     */
    protected $model;

    /**
     * Create a new database user provider.
     *
     * @param  \Illuminate\Contracts\Hashing\Hasher  $hasher
     * @param  string  $model
     * @return void
     */
    public function __construct(HasherContract $hasher, $model)
    {
        $this->model = $model;
        $this->hasher = $hasher;
    }
    ....
      /**
     * Validate a user against the given credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
     * @param  array  $credentials
     * @return bool
     */
    public function validateCredentials(UserContract $user, array $credentials)
    {
        $plain = $credentials['password'];

        return $this->hasher->check($plain, $user->getAuthPassword());
    }
    .....

通過這個,我們可以看出,這里面在構造方法注入了hash的驅動,然后在驗證的時候調用了hash的檢查函數去驗證用戶的密碼是否正確,也就是說,我們只要替換了這個hash驅動就可以解決問題了。

那么我們開始做,首先,我們需要去實現laravel的hash接口。弄一個md5的類出來。

<?php

namespace Tools\MD5;

use Illuminate\Contracts\Hashing\Hasher;

class MD5 implements Hasher
{
    /**
     * Hash the given value.
     *
     * @param string $value
     *
     * @return array  $options
     * @return string
     */
    public function make($value, array $options = [])
    {
        return md5($value);
    }

    /**
     * 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 = [])
    {
        return $this->make($value) === $hashedValue;
    }

    /**
     * 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 = [])
    {
        return false;
    }
}

這個類你可以自己手動創建在自己對應的文件夾。

然后我們創建一個provider,php artisan make:provider RiskUserProvider。
這個類就是關鍵了。
我們在這個類下,需要直接繼承Illuminate\Auth\EloquentUserProvider,這樣它的許多方法我們都不需要去重寫了,我們只要重寫它的構造函數。

<?php

namespace App\Providers;

use Auth;
use Illuminate\Auth\EloquentUserProvider;

class RiskUserProvider extends EloquentUserProvider
{
  public function __construct($hasher, $model)
  {
      parent::__construct($hasher, $model);
  }
}

最后,我們要將這個新的provider,注入auth。

        Auth::extend('riak', function($app){
            $model = $this->app['config']['auth.model'];

            return new RiskUserProvider(new MD5(), $model); //這里就是直接將我們新實現的md5類傳遞過去
        });

我們可以在AuthServiceProvider的boot方式注入就好了。
根據b35f1cb8a1fd這個朋友的反饋,5.2是使用Auth::provider方法,詳細我自己并沒有嘗試過,不過這位朋友成功了,謝謝這位朋友的反饋。

最后最后,我們在config/auth.php里面,替換驅動成riak。這樣問題就解決了。

這篇文章寫的時候,沒有詳細解釋laravel的容器,如果你覺得看起來晦澀難懂,是因為你沒有弄懂容器,詳細理解之后會看懂的,laravel的入門門檻確實比較高,對于新手來說可能非常不友好,但是當你理解了之后,會有很大的收獲的,克服它。

另外,其實這里的替換方式可以變成直接實現UserProvider的接口,替換整個Provider,這樣做會比較正規一點,基本做法和上面描述的都差不多。有錯誤的地方歡迎指正。

附上一篇參考資料

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容