应用启动后更改密码验证规则

Change password validation rules after application starts

我可以在启动后更新我的应用程序验证规则吗?

我试过类似的方法,但我对如何保留该信息感到困惑。

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?
}

提前致谢。抱歉我的英语不好:(.

如果我理解你正在尝试做什么,那么你正在尝试:

  • 修改密码验证器
  • 允许在 运行 时间内更改规则

然后您可以通过使用自定义密码验证器和您的 web.config 来存储值来实现这一点。我看到 web.config 的唯一问题是我认为在更改后它将重新启动您的 MVC 站点。如果这是一个问题,您可以创建一个管理页面,允许用户修改这些值,然后将这些值保存到数据库中。

要创建自定义验证器,您可以实现 IIdentityValidator 接口,然后在 UserManager 内部 class 在构造函数内将默认的 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