按照官方文档进行认证 发现无论怎么样都是失败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($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')); });