如何重写Laravel 的attempt方法呢?因为加密方法是自定义的。
程序员文章站
2022-05-01 08:18:22
...
Auth::attempt(array('username' => $username, 'password' => $password),false)
这个东西里头password是想用自己定义的方法加密
回复内容:
Auth::attempt(array('username' => $username, 'password' => $password),false)
这个东西里头password是想用自己定义的方法加密
文档确实没有写,但是我们可以看看源码
Auth方法的实现都在 Illuminate\Auth\Guard
里面
/**
* Attempt to authenticate a user using the given credentials.
*
* @param array $credentials
* @param bool $remember
* @param bool $login
* @return bool
*/
public function attempt(array $credentials = [], $remember = false, $login = true)
{
$this->fireAttemptEvent($credentials, $remember, $login);
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
// 看这里
// If an implementation of UserInterface was returned, we'll ask the provider
// to validate the user against the given credentials, and if they are in
// fact valid we'll log the users into the application and return true.
if ($this->hasValidCredentials($user, $credentials)) {
if ($login) {
$this->login($user, $remember);
}
return true;
}
return false;
}
/**
* Determine if the user matches the credentials.
*
* @param mixed $user
* @param array $credentials
* @return bool
*/
protected function hasValidCredentials($user, $credentials)
{
// 执行认证驱动器的validCredentials方法
return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
}
默认是使用eloquent作为认证驱动器,所以看看Illuminate\Auth\EloquentUserProvider
里面的实现
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
所以如果要改验证的逻辑,可以继承原有的驱动器,然后重写validateCredentials里面的逻辑
class TestUserProvider extend EloquentUserProvider
{
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return md5($plain) == $user->getAuthPassword();
}
}
最后设置驱动器,建议加载AppServiceProvider的boot()里面
Auth::setProvider(new TestUserProvider());
文档里有写!不要偷懒不看文档,你最近提的问题都是文档里写的。
上一篇: mysql操作_MySQL