How can I use MD5 hashing for passwords in Laravel?

♀尐吖头ヾ 提交于 2019-12-03 14:20:06

Check out the password mutator in your User Model. It's hashing the password another time after hashing it in the controller.

My recommendation is hash the password once in your creating() and updating() model events, and remove it from the mutator and controller.

step1: create app/libraries folder and add it to composer's autoload.classmap

"autoload": {
    "classmap": [
        // ...
        "app/libraries"
    ]
},

step 2: create two php file MD5Hasher.php and MD5HashServiceProvider in app/libraries MD5Hasher.php

<?php
namespace App\Libraries;
use Illuminate\Contracts\Hashing\Hasher;
class MD5Hasher implements Hasher {
    /**
     * Hash the given value.
     *
     * @param  string  $value
     * @return array   $options
     * @return string
     */
    public function make($value, array $options = array()) {
        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 = array()) {
        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 = array()) {
        return false;
    }
}

MD5HashServiceProvider.php

<?php
namespace App\Libraries;
use Illuminate\Support\ServiceProvider;
class MD5HashServiceProvider extends ServiceProvider {
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register() {
//        $this->app['hash'] = $this->app->share(function () {
//            return new MD5Hasher();
//        });
        $this->app->singleton('hash', function () {
            return new MD5Hasher();
        });
    }
    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides() {
        return array('hash');
    }

step3: Hide or Remove "Illuminate\Hashing\HashServiceProvider::class" in config/app.php and add "App\Libraries\MD5HashServiceProvider::class"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!