ASP.NET身份,需要“强大的”密码

也许我的googlin的技能今天早上不是很好,但我似乎无法find如何设置不同的密码要求(而不是最小/最大长度)与一个新的asp.net mvc5项目使用个人用户帐户。

[Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } 

我不知道我想要做什么密码要求,但可能是最小长度,需要一个小写字母,大写字母和数字的组合。

任何想法如何我可以做到这一点(通过模型属性最好)?

您可以将RegularExpressionAttribute与来自此答案的规则一起使用:

正则expression式validation密码强度

您可以在App_Start\IdentityConfig.csconfiguration密码要求

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

另一种select是创buildIIdentityValidator<string>的实现,并将其分配给UserManagerPasswordValidator属性。 它只有一个方法, ValidateAsync ,你可以在那里定义你喜欢的任何types的密码validation..我知道这与使用模型类中的属性一样远没有自动客户端validation一样的优点,但只是以为我会把它放在那里作为任何人的替代品。

例如

 public class CustomPasswordValidator : IIdentityValidator<string> { public int MinimumLength { get; private set; } public int MaximumLength { get; private set; } public CustomPasswordValidator(int minimumLength, int maximumLength) { this.MinimumLength = minimumLength; this.MaximumLength = maximumLength; } public Task<IdentityResult> ValidateAsync(string item) { if (!string.IsNullOrWhiteSpace(item) && item.Trim().Length >= MinimumLength && item.Trim().Length <= MaximumLength) return Task.FromResult(IdentityResult.Success); else return Task.FromResult(IdentityResult.Failed("Password did not meet requrements.")); } } 
 /*Passwords must be at least min. 8 and max. 16 characters in length, minimum of 1 lower case letter [az] and a minimum of 1 upper case letter [AZ] and a minimum of 1 numeric character [0-9] and a minimum of 1 special character: $ @ $ ! % * ? & + = # PASSWORD EXAMPLE : @Password1 */ pass = TextBoxPss1.Text; Regex regex = new Regex("^(?=.*[az])(?=.*[AZ])(?=.*\\d)(?=.*[$@$!%*?&+=#]) [A-Za-z\\d$@$!%*?&+=#]{8,16}$"); Match match = regex.Match(pass); if (match.Success) {TextBoxPss1.Text = "OK" }