如何在ASP中定义标识的密码规则。NET 5 MVC 6 (vNext)?

时间:2022-11-21 03:29:53

The default Identity provider provided in ASP.NET 5 has very strict password rules by default, requiring a lower case character, an upper case character, a non-alphanumeric character, and a number. I am looking for a way to change the password requirements for the provider.

在ASP中提供的默认标识提供程序。NET 5默认有非常严格的密码规则,需要一个小写字符、一个大写字符、一个非字母数字字符和一个数字。我正在寻找一种方法来更改提供程序的密码要求。

Previously in ASP.NET 4, the provider could be configured via the Web.config XML file, as previously answered. However ASP.NET 5 uses the new code based configuration pattern and it is unclear how to configure the identity.

以前在ASP。NET 4可以通过Web配置提供程序。配置XML文件,如前所述。然而ASP。NET 5使用了新的基于代码的配置模式,目前还不清楚如何配置标识。

How can I change the password requirements for my application?

如何更改应用程式的密码要求?

4 个解决方案

#1


118  

I actually ended up figuring this out, it turns out you need to supply AddDefaultIdentity with a suitable lambda expression that configures the IdentityOptions it provides. This is done inside the ConfigureServices method within the Startup class, like so:

实际上,我最终解决了这个问题,您需要为AddDefaultIdentity提供一个合适的lambda表达式,该表达式配置它提供的标识选项。这是在启动类的ConfigureServices方法中完成的,如下所示:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {

        // Add Identity services to the services container.
        services.AddDefaultIdentity<ApplicationIdentityDbContext, ApplicationUser, IdentityRole>(Configuration,
            o => {
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonLetterOrDigit = false;
                o.Password.RequiredLength = 7;
            });
    }
}

Update 2:

更新2:

The above was true in the beta1 versions of the framework, in the latest rc1 beta5 it has changed slightly to:

上述情况在该框架的beta1版本中是正确的,在最新的rc1 beta5中,它略有变化为:

services.AddIdentity<ApplicationUser, IdentityRole>(o => {
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationIdentityDbContext>()
.AddDefaultTokenProviders();

#2


8  

in startup.cs:

在startup.cs:

   services.AddIdentity<ApplicationUser, IdentityRole>(x =>
        {
            x.Password.RequiredLength = 6;
            x.Password.RequireUppercase = false;
            x.Password.RequireLowercase = false;
            x.Password.RequireNonAlphanumeric = false;
        }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

#3


8  

If you have set up a new Web project with Individual User Accounts go to:

如果您已经建立了一个新的Web项目,并拥有个人用户帐户,请转到:

App_Start -> IdentityConfig.cs

There you can edit the following defaults:

在那里,您可以编辑以下默认设置:

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

#4


5  

What I wanted to do was to customize the password rule so that it should contain characters from at least 2 of the following groups: lower case, upper case, digits and special symbols.

我想要做的是定制密码规则,以便它应该包含至少两个以下组中的字符:小写、大写、数字和特殊符号。

This is not something that I could do by just changing PasswordValidator options:

这不是我通过改变密码验证器选项就能做到的事情:

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

So instead I created a Custom validator by extending IIdentityValidator...

因此,我通过扩展IIdentityValidator创建了一个自定义验证器。

First, create a new file CustomPasswordValidator.cs in your Extensions folder:

首先,创建一个新的文件CustomPasswordValidator。扩展文件夹中的cs:

public class CustomPasswordValidator : IIdentityValidator<string>
{
    public int RequiredLength { get; set; }
    public CustomPasswordValidator(int length) {
        RequiredLength = length;
    }

    /* 
     * logic to validate password: I am using regex to count how many 
     * types of characters exists in the password
     */
    public Task<IdentityResult> ValidateAsync(string password) {
        if (String.IsNullOrEmpty(password) || password.Length < RequiredLength)
        {
            return Task.FromResult(IdentityResult.Failed(
                String.Format("Password should be at least {0} characters", RequiredLength)));
        }

        int counter = 0;
        List<string> patterns = new List<string>();
        patterns.Add(@"[a-z]");                                          // lowercase
        patterns.Add(@"[A-Z]");                                          // uppercase
        patterns.Add(@"[0-9]");                                          // digits
        patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\]]"); // special symbols

        // count type of different chars in password
        foreach (string p in patterns)
        {
            if (Regex.IsMatch(password, p)) {
                counter++;
            }
        }
        if (counter < 2)
        {
            return Task.FromResult(IdentityResult.Failed(
                "Please use characters from at least two of these groups: lowercase, uppercase, digits, special symbols"));
        }
        return Task.FromResult(IdentityResult.Success);
    }
}

Then go to IdentityConfig.cs, and initialize it in Create method:

然后去IdentityConfig。cs,在创建方法中初始化:

manager.PasswordValidator = new CustomPasswordValidator(6 /*min length*/);
        /*
        // You don't need this anymore
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        */

#1


118  

I actually ended up figuring this out, it turns out you need to supply AddDefaultIdentity with a suitable lambda expression that configures the IdentityOptions it provides. This is done inside the ConfigureServices method within the Startup class, like so:

实际上,我最终解决了这个问题,您需要为AddDefaultIdentity提供一个合适的lambda表达式,该表达式配置它提供的标识选项。这是在启动类的ConfigureServices方法中完成的,如下所示:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {

        // Add Identity services to the services container.
        services.AddDefaultIdentity<ApplicationIdentityDbContext, ApplicationUser, IdentityRole>(Configuration,
            o => {
                o.Password.RequireDigit = false;
                o.Password.RequireLowercase = false;
                o.Password.RequireUppercase = false;
                o.Password.RequireNonLetterOrDigit = false;
                o.Password.RequiredLength = 7;
            });
    }
}

Update 2:

更新2:

The above was true in the beta1 versions of the framework, in the latest rc1 beta5 it has changed slightly to:

上述情况在该框架的beta1版本中是正确的,在最新的rc1 beta5中,它略有变化为:

services.AddIdentity<ApplicationUser, IdentityRole>(o => {
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationIdentityDbContext>()
.AddDefaultTokenProviders();

#2


8  

in startup.cs:

在startup.cs:

   services.AddIdentity<ApplicationUser, IdentityRole>(x =>
        {
            x.Password.RequiredLength = 6;
            x.Password.RequireUppercase = false;
            x.Password.RequireLowercase = false;
            x.Password.RequireNonAlphanumeric = false;
        }).AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

#3


8  

If you have set up a new Web project with Individual User Accounts go to:

如果您已经建立了一个新的Web项目,并拥有个人用户帐户,请转到:

App_Start -> IdentityConfig.cs

There you can edit the following defaults:

在那里,您可以编辑以下默认设置:

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

#4


5  

What I wanted to do was to customize the password rule so that it should contain characters from at least 2 of the following groups: lower case, upper case, digits and special symbols.

我想要做的是定制密码规则,以便它应该包含至少两个以下组中的字符:小写、大写、数字和特殊符号。

This is not something that I could do by just changing PasswordValidator options:

这不是我通过改变密码验证器选项就能做到的事情:

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

So instead I created a Custom validator by extending IIdentityValidator...

因此,我通过扩展IIdentityValidator创建了一个自定义验证器。

First, create a new file CustomPasswordValidator.cs in your Extensions folder:

首先,创建一个新的文件CustomPasswordValidator。扩展文件夹中的cs:

public class CustomPasswordValidator : IIdentityValidator<string>
{
    public int RequiredLength { get; set; }
    public CustomPasswordValidator(int length) {
        RequiredLength = length;
    }

    /* 
     * logic to validate password: I am using regex to count how many 
     * types of characters exists in the password
     */
    public Task<IdentityResult> ValidateAsync(string password) {
        if (String.IsNullOrEmpty(password) || password.Length < RequiredLength)
        {
            return Task.FromResult(IdentityResult.Failed(
                String.Format("Password should be at least {0} characters", RequiredLength)));
        }

        int counter = 0;
        List<string> patterns = new List<string>();
        patterns.Add(@"[a-z]");                                          // lowercase
        patterns.Add(@"[A-Z]");                                          // uppercase
        patterns.Add(@"[0-9]");                                          // digits
        patterns.Add(@"[!@#$%^&*\(\)_\+\-\={}<>,\.\|""'~`:;\\?\/\[\]]"); // special symbols

        // count type of different chars in password
        foreach (string p in patterns)
        {
            if (Regex.IsMatch(password, p)) {
                counter++;
            }
        }
        if (counter < 2)
        {
            return Task.FromResult(IdentityResult.Failed(
                "Please use characters from at least two of these groups: lowercase, uppercase, digits, special symbols"));
        }
        return Task.FromResult(IdentityResult.Success);
    }
}

Then go to IdentityConfig.cs, and initialize it in Create method:

然后去IdentityConfig。cs,在创建方法中初始化:

manager.PasswordValidator = new CustomPasswordValidator(6 /*min length*/);
        /*
        // You don't need this anymore
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        */