首页 > 解决方案 > 密码重置时应用了不需要的验证规则

问题描述

我正在尝试使用 Laravel 身份验证的密码重置功能。运行make:auth命令后,在我的 ResetPasswordController 中,我覆盖了 Illuminate\Foundation\Auth\ResetsPasswords 特征的规则函数,如下所示:

protected function rules()
{
    return [
        'token' => 'required',
        'email' => 'required|email',
        'password' => 'required|confirmed|min:4',    
    ];
}

所以,我试图将最小长度值更改为 4。但是当我尝试重置密码时,仍然应用了至少 8 个字符的规则而不是 4。这是同一文件中 laravel的重置功能:

public function reset(Request $request)
{
    $request->validate($this->rules(), $this->validationErrorMessages());

    // Here we will attempt to reset the user's password. If it is successful we
    // will update the password on an actual user model and persist it to the
    // database. Otherwise we will parse the error and return the response.
    $response = $this->broker()->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    // If the password was successfully reset, we will redirect the user back to
    // the application's home authenticated view. If there is an error we can
    // redirect them back to where they came from with their error message.
    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($request, $response)
                : $this->sendResetFailedResponse($request, $response);
}

返回的$response是 Illuminate\Support\Facades\Password::INVALID_PASSWORD。我不明白这个规则是从哪里来的。实际上验证行为是这样的:当我输入少于 4 个字符时,我自己的规则被应用(正确)。但是,根据其他规则,输入 4 到少于 8 个字符也是错误的。

标签: laravelvalidationforgot-passwordbrokervalidationrules

解决方案


您收到错误的原因是因为PasswordBroker需要一个最小长度为 8 个字符的密码,所以即使您的表单验证通过了,验证PasswordBroker也没有。

解决此问题的一种方法是覆盖您的broker()方法ResetPasswordController并将您自己的验证器传递给它:

public function broker()
{
    $broker = Password::broker();

    $broker->validator(function ($credentials) {
        return $credentials['password'] === $credentials['password_confirmation'];
    });

    return $broker;
}

上面的内容本质上与本身发生的事情相同PasswordBroker,只是也没有进行字符串长度检查。

不要忘记将Password外观导入您的控制器:

use Illuminate\Support\Facades\Password;

这不是必需的,但为了更好地衡量,我建议password您也更新文件中的错误消息resources/lang/en/passwords.php


推荐阅读