我正在努力将Laravel的内置身份验证功能用于已包含用户名和密码的现有“用户”表。列名称为“UserEmail”和“UserPassword”。为了测试它,我使用修补程序创建一个条目,将密码哈希为:
$user->UserPassword=Hash::make('1234');
尝试使用Auth::attempt
登录时,身份验证会一直失败。为了进行调试,我开始添加var_dump
,甚至对数据库中的哈希密码进行的密码请求进行比较,并且匹配。所以我不确定为什么Auth::attempt
无法验证它:
这是我在LoginController.php中的功能:
public function login(Request $request)
{
// validate the form data
$this->validate($request, [
'UserEmail' => 'required',
'UserPassword' => 'required'
]);
var_dump($request->UserEmail);
var_dump($request->UserPassword);
$user = App\FarmUser::where('UserEmail', $request->UserEmail)->first();
var_dump($user->UserPassword);
$authenticated = Hash::check($request->UserPassword, $user->UserPassword);
var_dump($authenticated);
// attempt to log the user in
if (Auth::attempt(['UserEmail' => $request->UserEmail, 'UserPassword' => $request->UserPassword], $request->remember)) {
// if successful, then redirect to their intended location
Debugbar::addMessage('successfully authenticated');
return redirect()->intended($redirectTo);
}
// if unsuccessful, then redirect back to login with the form data
Debugbar::addMessage('authentication failed');
//return redirect()->back();
}
当我尝试登录时,我看到正确的UserEmail,UserPassword,并且哈希检查也返回true。但是,当我调用Auth::attempt
时,它无法成功进行身份验证并重定向回来。知道为什么我不能让Auth::attempt
正确验证吗?
当我登录时,这是从那些var转储生成的输出:
string(20) "user@test.com" string(8) "1234" string(60) "<hash>" bool(true)
以下是此App \ FarmUser模型的修补程序返回的内容:
>>> $user = App\FarmUser::where('UserLogin', 'testuser')->first();
=> App\FarmUser {#809
ID: 1,
UserLogin: "testuser",
password: "<hash>",
Active: "Yes",
UserEmail: "user@test.com",
Created: "2018-03-20 15:09:24",
CreatedByID: null,
Modified: null,
ModifiedByID: null,
created_at: "2018-03-20 19:09:09",
updated_at: "2018-03-20 19:09:09",
}
答案 0 :(得分:1)
您需要覆盖用户模型中的getAuthPassword()
方法,如下所示:
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->UserPassword;
}
请勿在{{1}}中致电UserPassword
,而是将其称为Auth::attempt()
。像这样:
password
这是因为Laravel无法识别哪些字段应该是Auth::attempt([
'UserEmail' => $request->UserEmail,
'password' => $request->UserPassword
]);
字段并且具有&#34;保留&#34; word&#34;密码&#34;对于它(它将在该字段上执行散列,但不对其他字段执行散列)。
编辑:
由于您的模型实际上是password
,您还需要在\App\FarmUser
文件中更改它,如下所示:
config/auth.php