我可以在启动后更新我的应用验证规则吗?
我尝试过这样的事情,但是我仍然坚持如何坚持这些信息。
public void UpdatePasswordValidation(SystemConfig config)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
manager.PasswordValidator = new CustomPasswordValidator
{
DigitLength = config.PswNumber ?? 0,
EspecialCharLength = config.PswEspecialChar ?? 0,
LowercaseLength = config.PswLower ?? 0,
RequiredLength = config.PswMinLength ?? 0,
UppercaseLength = config.PswUpper ?? 0,
};
//How do I persist these rules in owin context?
}
提前致谢。抱歉我的英语不好:(。
答案 0 :(得分:2)
如果我理解你想要做什么,那你就试图:
然后您可以通过使用自定义密码验证程序和web.config来存储值来实现此目的。我在web.config中看到的唯一问题是我认为在更改后它将重新启动您的MVC站点。如果这是一个问题,您可以创建一个管理页面,允许用户修改这些值,然后将值保存到数据库。
要创建自定义验证器,您可以使用IIdentityValidator接口,然后在构造函数内部的UserManager类内部替换自定义验证器的默认PasswordValidator。像这样:
public class CustomPasswordValidator : IIdentityValidator<string>
{
public int RequiredLength { get; set; }
public CustomPasswordValidator(int? length)
{
int webConfigMinimumPasswordLength;
if (int.TryParse(WebConfigurationManager.AppSettings["MinimumPasswordLength"],
out webConfigMinimumPasswordLength))
{
Console.WriteLine("Parsing config failed");
webConfigMinimumPasswordLength = 6; // just go back to default
}
RequiredLength = length ?? webConfigMinimumPasswordLength;
}
public Task<IdentityResult> ValidateAsync(string item)
{
if (String.IsNullOrEmpty(item) || item.Length < RequiredLength)
{
return Task.FromResult(IdentityResult.Failed(String.Format("Password should be of length {0}",RequiredLength)));
}
string pattern = @"^(?=.*[0-9])(?=.*[!@#$%^&*])[0-9a-zA-Z!@#$%^&*0-9]{10,}$";
if (!Regex.IsMatch(item, pattern))
{
return Task.FromResult(IdentityResult.Failed("Password should have one numeral and one special character"));
}
return Task.FromResult(IdentityResult.Success);
}
}
然后进入UserManager减速(通常在IdentityConfig.cs内)
public class ApplicationUserManager : UserManager<ApplicationUser[PR6] >
{
public ApplicationUserManager() : base(new UserStore<ApplicationUser(new ApplicationDbContext()))
{
// add the line below to your UserManager
PasswordValidator = new CustomPasswordValidator();
}
}
希望这会有所帮助,如果有任何问题可以随意发表评论,我无法将其纳入实际的MVC项目并确保我一起工作实际工作!
有关自定义密码验证器的更多信息,请查看:http://blogs.msdn.com/b/webdev/archive/2014/01/06/implementing-custom-password-policy-using-asp-net-identity.aspx