Laravel5.1自帶認證系統(Auth)改變加密方式帶來的思考

最近網站在進行重構,已經敲定使用laravel 5.11.1 LTS進行重構,這款框架的學習成本相對來說,還是較高,如果PHP知識不扎實的話,可能大部分時間都處于知其然不知其所以然的狀態,關于認證這一塊我也是摸索著看源碼才慢慢懂究竟怎么使用的。
初期遇到的問題如下:

  1. Auth認證加密方式的改變,舊版使用md5的加密方式,如何才能讓laravel轉換成md5認證。
  2. laravel認證的原理是怎么樣的。

其實本質上這是兩個問題,也是一個問題,因為如果我明白了laravel是如何進行認證的,基本也能改認證形式。

于是開始在各個地方尋找解決問題的方案,起手在google搜laravel md5,其實大部分人都不建議使用md5的方式來做用戶密碼的保存。于是慢慢的我的思路轉變為,如果將md5轉化為Bcrypt。

在網上搜了很多資料,其實沒有特別的幫助我去理解這個認證系統,大部分資料都只告訴了怎么做,于是就自己開始讀源碼了。
vendor/laravel/framework/src/Illuminate/Auth/Guard.php下,認證系統的邏輯就在這里面,登錄使用的函數源碼如下:

    /**
     * Attempt to authenticate a user using the given credentials.
     *
     * @param  array  $credentials
     * @param  bool   $remember
     * @param  bool   $login
     * @return bool
     */
    public function attempt(array $credentials = [], $remember = false, $login = true)
    {
        $this->fireAttemptEvent($credentials, $remember, $login);
        //下面這句對用戶名進行了驗證
        $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)) {//這里對密碼進行了驗證,因此要探究加密方式就要從這里看起
            if ($login) {
                $this->login($user, $remember);
            }

            return true;
        }

        return false;
    }

    /**
     * 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);
    }

代碼寫得很漂亮,很容易看得懂,跟著作者的邏輯跑,在$this->provider->retrieveByCredentials($credentials);中,laravel驗證了用戶是否存在
驗證邏輯的實現在vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php
源碼如下:

    /**
     * Retrieve a user by the given credentials.
     *
     * @param array $credentials
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        // 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')) {
                $query->where($key, $value);
            }
        }

        return $query->first();
    }

    /**
     * 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());
    }

上面這兩個函數就不做贅述了,之后就是最關鍵的密碼認證方面了,密碼認證函數是寫在vendor/laravel/framework/src/Illuminate/Hashing/BcryptHasher
我們想要的check和make函數就在這里:

    /**
     * Hash the given value.
     *
     * @param string $value
     * @param array  $options
     *
     * @return string
     *
     * @throws \RuntimeException
     */
    public function make($value, array $options = [])
    {
        $cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;

        $hash = password_hash($value, PASSWORD_BCRYPT, ['cost' => $cost]);

        if ($hash === false) {
            throw new RuntimeException('Bcrypt hashing not supported.');
        }

        return $hash;
    }

    /**
     * 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 = [])
    {
        if (strlen($hashedValue) === 0) {
            return false;
        }
        
        return password_verify($value, $hashedValue);//關于這個函數可以直接搜索php password_verify。
    }

是的,沒錯,你可以直接修改這里來改變你的加密方式,但是這種做法是不科學的,如果你沒有對這個框架爛熟于心,我不建議你直接對源碼進行修改!不建議!因為你并不知道改變源碼會對你的項目帶來什么影響!鑒于這個原因,以及我又很想使用laravel自帶的Auth認證系統(廢話,能省事怎么會不想用)。于是我打算改變加密策略,對我的密碼加密進行升級。具體的實現思路,就是讓用戶先進行判斷用戶的密碼以及賬號是否正確,如果正確則將新版密碼替換舊版密碼存進數據庫。然后進行用戶登錄。

      if ($user) {
            if (MD5Hasher::check($password,$user->user_password)){
                $user->user_password = Hash::make($password);
                $user->save();
            }
        }

思路大概如上。
總體來說,在用戶數量不是很多的情況下,這種方式還是可以接受的,日后用戶全部轉換回來之后,可以去除掉這一層檢查。關于如何檢查用戶是否全部升級完密碼,檢查密碼長度則可。

后記,這里必須提一個問題就是,使用attempt登錄,laravel是直接在調用了getAuthPassword,里面返回的是this->password,如果你數據庫里面的用戶表,密碼存儲的字段并不是password,而是其他,例如mypassword,則在UserModel改寫`getAuthPassword`成`returnthis->mypassword`。

添加多一種方法,如果你不想修改源碼,但是也想替換的話,那么,你可以通過容器去解決這個問題,laravel的設計確實很巧妙。詳細你可以參考我的另外一篇文章

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

推薦閱讀更多精彩內容