您可以在 MVC 中添加密码验证的地方?

Places you can add password validation in MVC?

我在 "ForgotPassword" 之后有一个 "ForceChangePassword" 页面,它在 "NewPassword" 字段上随机提出两个长度要求。问题是,我从来没有添加 7 的长度要求,也不知道它来自哪里或如何更改它。

来自 ModelState 的错误

The New password must be at least 6 characters long.
The 'New password' field is an invalid password. Password must have 7 or more characters.

if (!ModelState.IsValid) { return View(model); } // Only line executed in the POST Action.

我通过属性将 ViewModel 的长度要求设置为 6(见下文)。我不知道 7 的要求是从哪里来的。

IdentityConfig.cs

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

型号

[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[MembershipPassword(
    MinRequiredNonAlphanumericCharacters = 1,
    MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, etc).",
    ErrorMessage = "Your password must be 6 characters long and contain at least one symbol (!, @, #, etc)."
)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

查看

<div class="form-group">
    @Html.LabelFor(m => m.NewPassword, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.PasswordFor(m => m.NewPassword, new { @class = "form-control", @autocomplete = "off" })
    </div>
</div>

罪魁祸首属性:

data-val-password-min="7"

问题:在使用 Identity 2.0 的 MVC 5 项目中添加密码长度验证的可能位置在哪里?是否有某种我没有设置的默认要求?

注意: 如有必要,我会添加更多代码,但我已经发布了我所知道的所有可能相关的代码。其他都没有提到密码(据我所知,如果有更多位置,请告诉我)。

找到了。我猜 MembershipPassword 属性的默认长度为 7。它有双倍长度要求,仅仅是因为该属性有长度要求,而我也有一个 StringLength 属性。所以它对两者都抛出了错误。

修正:

[Required]
[MembershipPassword(
    MinRequiredNonAlphanumericCharacters = 1,
    MinNonAlphanumericCharactersError = "Your password needs to contain at least one symbol (!, @, #, etc).",
    ErrorMessage = "Your password must be 6 characters long and contain at least one symbol (!, @, #, etc).",
    MinRequiredPasswordLength = 6
)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

(设置 MinRequiredPasswordLength 并移除 StringLength 属性)

App_Start\IdentityConfig.cs中有以下代码:

// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

这就是你需要改变的。 [MembershipPassword] 来自旧的 ASP.NET 成员身份验证,它与身份完全不同且独立。