如何在laravel 4中匹配输入密码和数据库哈希密码


How to match input password and database hash password in laravel 4

如何从Laravel的给定请求验证用户密码?如何根据数据库中存储的密码散列检查密码?

首先,您需要根据电子邮件地址或用户名找到正在登录的用户,例如:

$user = User::where('email', '=', 'email@address.com')->first();

然后,您需要检查散列密码,如下所示:

Hash::check('INPUT PASSWORD', $user->password);

这将根据密码是否匹配返回true或false。

Laravel Login Authentication:

public function login(Request $request)
{
     $email = $request->input('email');
     $password = $request->input('password');
     $user = User::where('email', '=', $email)->first();
     if (!$user) {
        return response()->json(['success'=>false, 'message' => 'Login Fail, please check email id']);
     }
     if (!Hash::check($password, $user->password)) {
        return response()->json(['success'=>false, 'message' => 'Login Fail, pls check password']);
     }
        return response()->json(['success'=>true,'message'=>'success', 'data' => $user])
}

步骤1:首先从数据库获取用户数据

$user = User::where('email', '=', $request->input('email'))->first();

步骤2:获取用户密码

$user->password

步骤3:验证它为

 if(Hash::check($password, $user->password)) {
        return response()->json(['status'=>'true','message'=>'Email is correct']);
    } else {
        return response()->json(['status'=>'false', 'message'=>'password is wrong']);
    }

呜呼! !你已经完成了:)

 $email = Input::get('email');
    $user = User::where('email', '=', $email)->first();
    if (!$user) {
        return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
    }
    if (!Hash::check(Input::get('password'), $user->password)) {
        return response()->json(['success'=>false, 'message' => 'Not Login successfull']);
    }
    return response()->json(['success'=>true,'message'=>'success', 'data' => $user]);

从Laravel 5开始,您可以使用bcrypt()函数来散列明文。因此,您可以将散列密码保存在DB中,然后再次比较散列密码是否匹配。

$save_password = bcrypt('plain_text_password');
$check_password = bcrypt('provided_password_while_login_request');

然后,比较这两个。你可以走了。

或者,如果你想用Laravel的方式:

 $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        // Authentication passed...
        return redirect()->intended('dashboard');
    }

根据Laravel文档,我引用:"尝试方法接受一个键/值对数组作为它的第一个参数。数组中的值将用于在数据库表中查找用户。因此,在上面的示例中,将通过email列的值检索用户。如果找到用户,存储在数据库中的散列密码将与通过数组传递给方法的密码值进行比较。不应该对指定为密码值的密码进行散列,因为框架会在将该值与数据库中的散列密码进行比较之前自动对其进行散列。如果两个散列密码匹配,将为用户启动一个经过身份验证的会话。

如果身份验证成功,尝试方法将返回true。否则,返回false。"

您可以创建以下方法来查找laravel网站上关于身份验证的说明:

public function authenticate(Request $request)
{
    $credentials = $request->only('email', 'password');
    if (Auth::attempt($credentials)) {
        // Authentication passed...
        // use the below code to redirect the user to dashboard.
        // return redirect()->intended('dashboard');
    }
}

请查看以下链接,了解更多有关laravel网站认证的详细信息:https://laravel.com/docs/5.6/authentication用户身份验证