關於laravel框架的Auth::attempt驗證失敗

按照官方文檔進行認證 發現無論怎麼樣都是失敗php

if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
    // 用戶狀態永久保存...
}

研究他的源代碼 Auth定義在 vendor/laravel/framework/src/Illuminate/Auth laravel

attempt方法在Guard.php 這個方法最關鍵的就是 $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); 這一句數組

$credentials就是咱們上面傳進來的數組了 此時var_dump($user) 這個變量是正確 有值的 因此也就是if ($this->provider->validateCredentials($user, $credentials)) 這句驗證沒經過session

$provider 這個屬性的定義app

    /**
     * The user provider implementation.
     *
     * @var \Illuminate\Auth\UserProviderInterface
     */
    protected $provider;
UserProviderInterface 是一個抽象類
聯繫到 config/auth.php 中 driver 項有 Supported: "database", "eloquent" 因此 DatabaseUserProvider 或 EloquentUserProvider就是具體的實現了
validateCredentials 方法定義
	/**
	 * Validate a user against the given credentials.
	 *
	 * @param  \Illuminate\Auth\UserInterface  $user
	 * @param  array  $credentials
	 * @return bool
	 */
	public function validateCredentials(UserInterface $user, array $credentials)
	{
		$plain = $credentials['password'];

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

$hasher 在 Illuminate\Hashing\HasherInterfaceide

官方文檔有這一句 The Laravel Hash class provides secure Bcrypt hashing: 也就是 BcryptHasher類的check方法ui

	/**
	 * 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 password_verify($value, $hashedValue);
	}

用的是password_verify 跟咱們經常使用的md5什麼的徹底不搭 難怪失敗  this

找到緣由但在官方文檔沒找到解決的方法 無奈用 auth attempt md5  password hash等關鍵字google 才發現實際上是有文檔的  可見細心是多麼重要google

http://laravel.com/docs/extending#authenticationspa

接着本身新建一個類 class HeyliUserProvider implements UserProviderInterface  密碼驗證方法validateCredentials就能夠徹底按照本身的業務邏輯了

Auth::extend('heyli',function($appextend的第一個參數也就是驗證方式的名稱了 把 config/auth.php中的driver變成相對應的就能夠了

PS:當你用戶表主鍵不是 ID或密碼字段不是password 的時候就會出錯了  return new GenericUser((array) $user);   GenericUser類有下面方法

    /**
     * Get the unique identifier for the user.
     *
     * @return mixed
     */
    public function getAuthIdentifier()
    {
        return $this->attributes['id'];
    }

    /**
     * Get the password for the user.
     *
     * @return string
     */
    public function getAuthPassword()
    {
        return $this->attributes['password'];
    }

此時在HeyliUserProvider 這個類中的 retrieveById retrieveByCredentials 這兩個方法 添加 

if ( ! is_null($user))
{
$user->id = (string) $user->uid;  //添加這一句 像個人主鍵是UID  
return new GenericUser((array) $user);
}

最後記得在 app/start/global.php 添加上

Auth::extend('heyli', function($app) {
    $provider =  new \Example\Auth\HeyliUserProvider();

    return new \Illuminate\Auth\Guard($provider, App::make('session.store'));
});
相關文章
相關標籤/搜索