按照官方文檔進行認證 發現不管怎么樣都是失敗
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// 用戶狀態永久保存...
}
研究他的源代碼 Auth定義在 vendor/laravel/framework/src/Illuminate/Auth
attempt方法在Guard.php 這個方法最關鍵的就是 $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials); 這一句
$credentials就是我們上面傳進來的數組了 此時var_dump($user) 這個變量是正確 有值的 所以也就是if ($this->provider->validateCredentials($user, $credentials)) 這句驗證沒通過
$provider 這個屬性的定義
/** * 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\HasherInterface
官方文檔有這一句 The Laravel Hash class provides secure Bcrypt hashing: 也就是 BcryptHasher類的check方法
/**
* 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什么的完全不搭 難怪失敗
找到原因但在官方文檔沒找到解決的方法 無奈用 auth attempt md5 password hash等關鍵字google 才發現其實是有文檔的 可見細心是多么重要
http://laravel.com/docs/extending#authentication
接着自己新建一個類 class HeyliUserProvider implements UserProviderInterface 密碼驗證方法validateCredentials就可以完全按照自己的業務邏輯了
Auth::extend('heyli',function($app) extend的第一個參數也就是驗證方式的名稱了 把 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'));
});
