1. 程式人生 > >修改laravel5.3的密碼驗證

修改laravel5.3的密碼驗證

如何使用自定義的密碼加密和驗證方法?從網上找到了解決辦法,現記錄下來,一方面加深印象,另一方面寫成blog備查。

從這篇文章可以瞭解laravel的認證流程:http://www.tuicool.com/articles/Av2aMb2。

按照文章中的辦法,在app下新建資料夾hash,然後新建兩個類檔案:EloquentUserProvider.php和Security.php

Security.php內容:

namespace App\hash;

use Illuminate\Contracts\Hashing\Hasher;

/**
 * 加密類庫,移植自Yii2.0的Security類
 */
class Security implements Hasher
{
   
    public $passwordHashCost = 13;

    private $_useLibreSSL;
    private $_randomFile;

    /**
     * Generates specified number of random bytes.
     * Note that output may not be ASCII.
     * @see generateRandomString() if you need a string.
     *
     * @param integer $length the number of bytes to generate
     * @return string the generated random bytes
     * @throws InvalidParamException if wrong length is specified
     * @throws Exception on failure.
     */
    public function generateRandomKey($length = 32)
    {
        if (!is_int($length)) {
            throw new Exception('First parameter ($length) must be an integer');
        }

        if ($length < 1) {
            throw new Exception('First parameter ($length) must be greater than 0');
        }

        // always use random_bytes() if it is available
        if (function_exists('random_bytes')) {
            return random_bytes($length);
        }

        // The recent LibreSSL RNGs are faster and likely better than /dev/urandom.
        // Parse OPENSSL_VERSION_TEXT because OPENSSL_VERSION_NUMBER is no use for LibreSSL.
        // https://bugs.php.net/bug.php?id=71143
        if ($this->_useLibreSSL === null) {
            $this->_useLibreSSL = defined('OPENSSL_VERSION_TEXT')
                && preg_match('{^LibreSSL (\d\d?)\.(\d\d?)\.(\d\d?)$}', OPENSSL_VERSION_TEXT, $matches)
                && (10000 * $matches[1]) + (100 * $matches[2]) + $matches[3] >= 20105;
        }

        // Since 5.4.0, openssl_random_pseudo_bytes() reads from CryptGenRandom on Windows instead
        // of using OpenSSL library. LibreSSL is OK everywhere but don't use OpenSSL on non-Windows.
        if ($this->_useLibreSSL
            || (
                DIRECTORY_SEPARATOR !== '/'
                && substr_compare(PHP_OS, 'win', 0, 3, true) === 0
                && function_exists('openssl_random_pseudo_bytes')
            )
        ) {
            $key = openssl_random_pseudo_bytes($length, $cryptoStrong);
            if ($cryptoStrong === false) {
                throw new Exception(
                    'openssl_random_pseudo_bytes() set $crypto_strong false. Your PHP setup is insecure.'
                );
            }
            if ($key !== false && StringHelper::byteLength($key) === $length) {
                return $key;
            }
        }

        // mcrypt_create_iv() does not use libmcrypt. Since PHP 5.3.7 it directly reads
        // CryptGenRandom on Windows. Elsewhere it directly reads /dev/urandom.
        if (function_exists('mcrypt_create_iv')) {
            $key = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
            if (StringHelper::byteLength($key) === $length) {
                return $key;
            }
        }

        // If not on Windows, try to open a random device.
        if ($this->_randomFile === null && DIRECTORY_SEPARATOR === '/') {
            // urandom is a symlink to random on FreeBSD.
            $device = PHP_OS === 'FreeBSD' ? '/dev/random' : '/dev/urandom';
            // Check random device for special character device protection mode. Use lstat()
            // instead of stat() in case an attacker arranges a symlink to a fake device.
            $lstat = @lstat($device);
            if ($lstat !== false && ($lstat['mode'] & 0170000) === 020000) {
                $this->_randomFile = fopen($device, 'rb') ?: null;

                if (is_resource($this->_randomFile)) {
                    // Reduce PHP stream buffer from default 8192 bytes to optimize data
                    // transfer from the random device for smaller values of $length.
                    // This also helps to keep future randoms out of user memory space.
                    $bufferSize = 8;

                    if (function_exists('stream_set_read_buffer')) {
                        stream_set_read_buffer($this->_randomFile, $bufferSize);
                    }
                    // stream_set_read_buffer() isn't implemented on HHVM
                    if (function_exists('stream_set_chunk_size')) {
                        stream_set_chunk_size($this->_randomFile, $bufferSize);
                    }
                }
            }
        }

        if (is_resource($this->_randomFile)) {
            $buffer = '';
            $stillNeed = $length;
            while ($stillNeed > 0) {
                $someBytes = fread($this->_randomFile, $stillNeed);
                if ($someBytes === false) {
                    break;
                }
                $buffer .= $someBytes;
                $stillNeed -= StringHelper::byteLength($someBytes);
                if ($stillNeed === 0) {
                    // Leaving file pointer open in order to make next generation faster by reusing it.
                    return $buffer;
                }
            }
            fclose($this->_randomFile);
            $this->_randomFile = null;
        }

        throw new Exception('Unable to generate a random key');
    }

    /**
     * Generates a random string of specified length.
     * The string generated matches [A-Za-z0-9_-]+ and is transparent to URL-encoding.
     *
     * @param integer $length the length of the key in characters
     * @return string the generated random key
     * @throws Exception on failure.
     */
    public function generateRandomString($length = 32)
    {
        if (!is_int($length)) {
            throw new Exception('First parameter ($length) must be an integer');
        }

        if ($length < 1) {
            throw new Exception('First parameter ($length) must be greater than 0');
        }

        $bytes = $this->generateRandomKey($length);
        // '=' character(s) returned by base64_encode() are always discarded because
        // they are guaranteed to be after position $length in the base64_encode() output.
        return strtr(substr(base64_encode($bytes), 0, $length), '+/', '_-');
    }

    /**
     * Generates a secure hash from a password and a random salt.
     *
     * The generated hash can be stored in database.
     * Later when a password needs to be validated, the hash can be fetched and passed
     * to [[validatePassword()]]. For example,
     *
     * ```php
     * // generates the hash (usually done during user registration or when the password is changed)
     * $hash = Yii::$app->getSecurity()->generatePasswordHash($password);
     * // ...save $hash in database...
     *
     * // during login, validate if the password entered is correct using $hash fetched from database
     * if (Yii::$app->getSecurity()->validatePassword($password, $hash) {
     *     // password is good
     * } else {
     *     // password is bad
     * }
     * ```
     *
     * @param string $password The password to be hashed.
     * @param integer $cost Cost parameter used by the Blowfish hash algorithm.
     * The higher the value of cost,
     * the longer it takes to generate the hash and to verify a password against it. Higher cost
     * therefore slows down a brute-force attack. For best protection against brute-force attacks,
     * set it to the highest value that is tolerable on production servers. The time taken to
     * compute the hash doubles for every increment by one of $cost.
     * @return string The password hash string. When [[passwordHashStrategy]] is set to 'crypt',
     * the output is always 60 ASCII characters, when set to 'password_hash' the output length
     * might increase in future versions of PHP (http://php.net/manual/en/function.password-hash.php)
     * @throws Exception on bad password parameter or cost parameter.
     * @see validatePassword()
     */
    public function generatePasswordHash($password, $cost = null)
    {
        if ($cost === null) {
            $cost = $this->passwordHashCost;
        }

        if (function_exists('password_hash')) {
            /** @noinspection PhpUndefinedConstantInspection */
            return password_hash($password, PASSWORD_DEFAULT, ['cost' => $cost]);
        }

        $salt = $this->generateSalt($cost);
        $hash = crypt($password, $salt);
        // strlen() is safe since crypt() returns only ascii
        if (!is_string($hash) || strlen($hash) !== 60) {
            throw new Exception('Unknown error occurred while generating hash.');
        }

        return $hash;
    }

    /**
     * Verifies a password against a hash.
     * @param string $password The password to verify.
     * @param string $hash The hash to verify the password against.
     * @return boolean whether the password is correct.
     * @throws InvalidParamException on bad password/hash parameters or if crypt() with Blowfish hash is not available.
     * @see generatePasswordHash()
     */
    public function validatePassword($password, $hash)
    {
        if (!is_string($password) || $password === '') {
            throw new Exception('Password must be a string and cannot be empty.');
        }

        if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hash, $matches)
            || $matches[1] < 4
            || $matches[1] > 30
        ) {
            throw new Exception('Hash is invalid.');
        }

        if (function_exists('password_verify')) {
            return password_verify($password, $hash);
        }

        $test = crypt($password, $hash);
        $n = strlen($test);
        if ($n !== 60) {
            return false;
        }

        return $this->compareString($test, $hash);
    }

    /**
     * Generates a salt that can be used to generate a password hash.
     *
     * The PHP [crypt()](http://php.net/manual/en/function.crypt.php) built-in function
     * requires, for the Blowfish hash algorithm, a salt string in a specific format:
     * "$2a$", "$2x$" or "$2y$", a two digit cost parameter, "$", and 22 characters
     * from the alphabet "./0-9A-Za-z".
     *
     * @param integer $cost the cost parameter
     * @return string the random salt value.
     * @throws InvalidParamException if the cost parameter is out of the range of 4 to 31.
     */
    protected function generateSalt($cost = 13)
    {
        $cost = (int) $cost;
        if ($cost < 4 || $cost > 31) {
            throw new Exception('Cost must be between 4 and 31.');
        }

        // Get a 20-byte random string
        $rand = $this->generateRandomKey(20);
        // Form the prefix that specifies Blowfish (bcrypt) algorithm and cost parameter.
        $salt = sprintf("$2y$%02d$", $cost);
        // Append the random salt data in the required base64 format.
        $salt .= str_replace('+', '.', substr(base64_encode($rand), 0, 22));

        return $salt;
    }

    /**
     * Performs string comparison using timing attack resistant approach.
     * @see http://codereview.stackexchange.com/questions/13512
     * @param string $expected string to compare.
     * @param string $actual user-supplied string.
     * @return boolean whether strings are equal.
     */
    public function compareString($expected, $actual)
    {
        $expected .= "\0";
        $actual .= "\0";
        $expectedLength = StringHelper::byteLength($expected);
        $actualLength = StringHelper::byteLength($actual);
        $diff = $expectedLength - $actualLength;
        for ($i = 0; $i < $actualLength; $i++) {
            $diff |= (ord($actual[$i]) ^ ord($expected[$i % $expectedLength]));
        }
        return $diff === 0;
    }

    public function make($value, array $options = [])
    {
        return $this->generatePasswordHash($value);
    }

    public function check($password, $hashedValue, array $options = [])
    {
        if (!is_string($password) || $password === '') {
            throw new Exception('Password must be a string and cannot be empty.');
        }

        if (!preg_match('/^\$2[axy]\$(\d\d)\$[\.\/0-9A-Za-z]{22}/', $hashedValue['password'], $matches)
            || $matches[1] < 4
            || $matches[1] > 30
        ) {
            throw new Exception('Hash is invalid.');
        }

        if (function_exists('password_verify')) {
            
            return password_verify($password, $hashedValue['password']);
        }

        $test = crypt($password, $hashedValue['password']);
        $n = strlen($test);
        if ($n !== 60) {
            return false;
        }

        return $this->compareString($test, $hashedValue['password']);
    }

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

類中實現了3個方法:make -- 加密密碼,check -- 校驗密碼,needsRehash -- 暫不支援。

新註冊使用者時,將會呼叫make方法生成加密的密碼;使用者登入時,呼叫check校驗密碼。

EloquentUserProvider.php內容:

<?php
namespace App\hash;

use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Str;

class EloquentUserProvider extends EloquentUserProvider
{

	/**
	 * Validate a user against the given credentials.
	 *
	 * @param \Illuminate\Contracts\Auth\Authenticatable $user
	 * @param array $credentials
	 * @return bool
	 */
	public function validateCredentials(Authenticatable $user, array $credentials)
	{
		$plain = $credentials['password'];
		$authPassword = $user->getAuthPassword();
		//return bcrypt($plain) === $authPassword['password'];
		return $this->hasher->check($plain, $authPassword);
	}
}

類中實現了一個方法:validateCredentials -- 校驗使用者密碼

然後需要修改User類,新增getAuthPassword方法:

public function getAuthPassword()
    {
        return ['password' => $this->attributes['password_hash']];
    }

使用命令列:

php artisan make:provider HashServiceProvider

此命令會在app/Providers下建立檔案:HashServiceProvider.php,開啟這個檔案,在register方法中新增下面程式碼:

$this->app['hash'] = $this->app->share(function() {
    return new \App\hash\Security();
});
上面的程式碼註冊新的hash類為剛才的Security類。

修改config/app.php檔案引用介面卡:

//註釋掉這一行
//Illuminate\Hashing\HashServiceProvider::class,
//新增下面這一行
App\Providers\HashServiceProvider::class,

做完上述工作後,需要修改laravel的Auth介面卡為我們自己的介面卡:

開啟app/Providers/AuthServiceProvider.php,修改boot方法:

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

        \Auth::provider('my-eloquent', function($app, $config) {
            return new \App\hash\EloquentUserProvider($this->app['hash'], $config['model']);
        });
    }
開啟config/auth.php,修改providers陣列內容:
'users' => [
            'driver' => 'my-eloquent',
            'model' => App\User::class,
        ],
至此,修改完畢,經測試註冊和登入驗證均正常。


相關推薦

修改laravel5.3密碼驗證

如何使用自定義的密碼加密和驗證方法?從網上找到了解決辦法,現記錄下來,一方面加深印象,另一方面寫成blog備查。 從這篇文章可以瞭解laravel的認證流程:http://www.tuicool.com/articles/Av2aMb2。 按照文章中的辦法,在app下新建

laravel 修改使用者模組密碼驗證

Larval 5.2的預設Auth登陸傳入郵件和使用者密碼到attempt 方法來認證,通過email 的值獲取,如果使用者被找到,經雜湊運算後儲存在資料中的password將會和傳遞過來的經雜湊運算處理的passwrod值進行比較。如果兩個經雜湊運算的密碼相匹配那麼將會為這個使用者開啟一個認證

laravel5 3驗證方式

做專案的時候,大家都知道要驗證。那麼今天我就說說laravel的3種驗證方式: 1、手動建立驗證器:該驗證規則就寫到控制器裡面,造成控制器程式碼太多,個人認為不美觀; 2、表單請求驗證:該方法驗證,相信大家常用。在此之前,我都是用表單驗證,前兩種驗證方式在laravel文

登陸密碼驗證,超過3次退出

class 密碼驗證 put pan col 錯誤 用戶 密碼 cnblogs import getpass i = 3 while i > 0: x = input (‘請輸入用戶名:‘) y = getpass.getpass(‘請輸入密碼:‘)

通用的前端修改密碼驗證

ctype window pass 驗證 tab 提交 col conf [0 <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>修改密碼

django 用戶管理(3)--編輯用戶 and 修改用戶密碼

ons == 服務器 .get 網頁 checked his === arr 編輯用戶 1、點擊編輯按鈕 流程:(1)、禁用編輯的herf,避免跳轉到其他網頁href="javascript:void(0)" (2)、需要給“編輯”按鈕添加class 為

jQuery+ajax實現修改密碼驗證

修改密碼是比較簡單的功能,要求如下: 1、原密碼必須輸入正確,才可以修改密碼 2、新密碼需在6-18位之間 3、第二次輸入的新密碼必須與第一次相同。 4、前三個條件同時滿足的時,修改密碼才能成功,否則顯示錯誤提示資訊。 5、錯誤提示資訊和驗證資訊全部使用ajax提交、響應

Laravel5.3~5.5 使用預設api驗證登陸

講解如何使用laravel5.3~5.5框架預設的api驗證登陸。 講道理 config/auth.php裡,預設guard有web和api 'guards' => [ 'web' => [ 'driver' =&g

Laravel5.3使用auth登入驗證

1.使用命令列直接設定 想要更快上手?只需要在新安裝的Laravel應用下執行php artisan make:auth ,然後在瀏覽器中訪問http://my/register ,該命令會生成使用者登入註冊所需要的所有東西。 Laravel 提供了幾個預置的認證控制

Oracle 修改本地賬戶密碼

ase user ack 微軟雅黑 margin cmd命令 sysdba 用戶名 system CMD 運行cmd命令行 錄入 sqlplus /nolog 無用戶名登錄 conn /as sysdba 連接到數據本地數據 alte

Discuz常見小問題2-如何修改管理員密碼修改admin賬戶密碼

scu pan image family 詳情 點擊 用戶管理 admin src 進入後臺,點擊用戶,用戶管理,搜索admin這個用戶找到,然後點擊詳情 ?輸入新密碼即可(無需驗證老的密碼) ? ? ? ? ?Discuz常見小問題

MySQL修改用戶密碼

修改用戶 isf 運行 卸載mysql top lte cat host cati #1.停止mysql數據庫 /etc/init.d/mysqld stop #2.執行如下命令 mysqld_safe --user=mysql --skip-grant-tables -

Python3.4 12306 2015年3驗證碼識別

like target bottom edr ocr extra spl apple creat import ssl import json from PIL import Image import requests import re import urllib.r

windows7 dos修改mysql root密碼

word 輸入 -s ima pan root密碼 同時按下 password 回車 第一步:打開mysql 安裝路徑 選擇bin文件 同時按下Shift+鼠標右鍵 點擊“在此處打開命令” 第二步:輸入mysql -u root -p 按回車鍵會提示輸入密碼 默

passwd修改用戶密碼

passwd語法:passwd[username]等創建完賬戶後,默認是沒有設置密碼的。雖然沒有密碼,但該賬戶同樣登錄不了系統。只有設置好密碼後才可以登錄系統。在為用戶創建密碼時,安全起見,請盡量設置復雜一些。建議按照以下規則設置密碼:(1)長度大於10個字符;(2)密碼中包含大小寫字母數字以及特殊字符 *

mysql 5.7 怎麽修改默認密碼、隨機密碼

server 狀態 program ide 是我 是什麽 修改密碼 tro .com 當你使用 mysql -u root -p 登陸mysql的時候,提示下方要輸入密碼。而這個密碼不是我們剛剛安裝mysql時設置的那個密碼。而且安裝完mysql 生成的隨機密碼 那麽我們在

centos6.5中部署Zeppelin並配置賬號密碼驗證

oop nbsp 開啟 art 變量 jdk 1.7 技術 apache 使用 centos6.5中部署Zeppelin並配置賬號密碼驗證1.安裝JavaZeppelin支持的操作系統如下圖所示。在安裝Zeppelin之前,你需要在部署的服務器上安裝Oracle JDK 1

Mac Mysql 修改初始化密碼

ble 設置 ges files run table 自動 初始 mysq 第一步: 點擊系統偏好設置->最下邊點MySQL,在彈出頁面中,關閉服務 第二步:進入終端輸入:cd /usr/local/mysql/bin/回車後 登錄管理員權限 sudo su回

laravel5.4生成驗證

validate jpeg mage 命令 不顯示 ace request 技術 執行c 總結:本篇博客介紹使用gregwar/captcha實現驗證碼的具體操作步驟,以及可能遇到的問題和解決辦法。 操作步驟: 1, 在laravel5.4項目根目錄下找到 composer

laravel5.3-數據庫操作下的局部or條件與全局or條件(orWhere的局部與全局)

bsp trim con pty 數據庫 區別 替換 derby 是我 當用戶名不為空時 SELECT * FROM `ACCOUNT_RECHARGE` LEFT JOIN `ORDER` ON `ACCOUNT_RECHARGE`.`OrderNo` = `ORDER`