提问者:小点点

Laravel 5.6-在自定义表上使用内置身份验证-不验证用户/密码


我正在努力使用Laravel的内置auth来对抗已经包含用户名和密码的现有“Users”表。列名为“UserEmail”和“UserPassword”。为了测试它,我使用tinker创建了一个条目,将密码散列为:

$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::trunt时,它不会成功地进行身份验证并重定向回来。你知道为什么我不能让Auth::trunt正确地进行身份验证吗?

当我登录时,这是从这些var转储生成的输出:

string(20) "user@test.com" string(8) "1234" string(60) "<hash>" bool(true)

以下是tinker为此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",
   }

共1个答案

匿名用户

您需要覆盖用户模型中的getAuthPassword()方法,如下所示:

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

不要在您的Auth::trunt()中调用UserPassword,而是调用它password。这样地:

Auth::attempt([
    'UserEmail' => $request->UserEmail, 
    'password' => $request->UserPassword
]);

这是因为Laravel无法识别哪些字段应该是密码字段,并且有一个“保留”字“密码”(它将对该字段执行哈希,但不会对其他字段执行哈希)。

编辑:

由于您的模型实际上是\App\FarmUser,您还需要在config/auth.php文件中更改它,如下所示:

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\FarmUser::class,
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],