密码重置时应用了不需要的验证规则

Unwanted validation rule being applied on password reset

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

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

因此,我尝试将最小长度值更改为 4。但是当我尝试重置密码时,仍然应用最少 8 个字符的规则,而不是 4 个。 这是同一文件中 laravel 的 reset 函数:

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 个字符也是一些其他规则的错误。

返回错误的原因是 PasswordBroker 要求密码的最小长度为 8 个字符,因此即使您的表单验证通过,[=12= 中的验证] 不是。

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

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;

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