Php 如何在Laravel中验证bcrypt密码?

Php 如何在Laravel中验证bcrypt密码?,php,laravel,validation,laravel-5,Php,Laravel,Validation,Laravel 5,我有一个更改密码表单,其中包含旧密码和新密码字段 “旧密码”字段名为“旧密码” 在我的控制器中,我像这样验证密码 $this->validate($request, [ 'old_password' => 'required|min:6|exists:users,password', 'password' => 'required|min:6:max:30', ]); 但是它不能像im那样直接比较旧的密码和没有bcrypt函数

我有一个更改密码表单,其中包含旧密码和新密码字段 “旧密码”字段名为“旧密码”

在我的控制器中,我像这样验证密码

$this->validate($request, [
            'old_password' => 'required|min:6|exists:users,password',
            'password' => 'required|min:6:max:30',
]); 
但是它不能像im那样直接比较旧的密码和没有bcrypt函数的密码

那么,我如何将旧的_密码字段与已存储的bcrypted password in user字段进行比较呢

注意:我想返回验证错误,密码没有 如果不同,则匹配


您需要比较旧密码和希望比较的其他密码的哈希结果

// when old_password is not encrypted but other_password is:
bcrypt('old_password') === hash_of_other_password

使用$this->validate而不是编写自定义规则的一种方法是使用$request->merge。这样,您就可以使用已确认的规则,甚至可以在数据库中存储哈希值的情况下使用已确认的规则。

这就是我创建此函数的方式

HTML表单

<form action="{{ url('admin/admin-admin-password-update/'.$admin->id) }}" method="post">
    {{ csrf_field() }}
    <div class="form-group {{ $errors->has('new_password') ? 'has-error' : '' }}">
        <label for="new_password" class="form-label">New Password (Minimum of 6 characters. No spaces.) <span class="required-alert">*</span></label>
        <input type="password" class="form-control" name="new_password" id="new_password" />

        @if ($errors->has('new_password'))
            <div class="help-block">
                 {{ $errors->first('new_password') }}
            </div>
       @endif

   </div>
   <div class="form-group {{ $errors->has('confirm_password') ? 'has-error' : '' }}">
        <label for="confirm_password" class="form-label">Confirm New Password <span class="required-alert">*</span></label>
        <input type="password" class="form-control" name="confirm_password" id="confirm_password" />

        @if ($errors->has('confirm_password'))
            <div class="help-block">
                 {{ $errors->first('confirm_password') }}
            </div>
       @endif

  </div>
  <div class="form-group clearfix">
     <button type="submit" class="btn btn-primary">Save New Password</button>
  </div>
 </form>

您需要为此使用自定义验证规则,或者扩展validatorthnx以提供完整的示例。虽然这可能会起作用,但这不是一个好的做法,因为它可能允许定时攻击来帮助确定所使用的哈希算法的类型。
public function updatePassword(Request $request)
{
    $this->admin = Auth::user();
    $this->id   = $this->admin->id;

    $this->validate($request, [
       'current_password'   => 'required',
       'password'           => 'required|min:6',
       'confirm_password'   => 'required|same:password',
    ]);

    if (Hash::check($request->input('current_password'), $this->admin->password)) {
        $this->admin->password = Hash::make($request->input('password'));

        $this->admin->save();

        return redirect()->back()->with('success', 'Your password has been updated.');
    } else {
        return redirect()->back()->with('warning', 'The current password you provided could not be verified');
    }
}