Program Tip

ASP.NET 5 MVC 6 (vNext)에서 ID에 대한 암호 규칙을 어떻게 정의합니까?

programtip 2020. 10. 31. 10:00
반응형

ASP.NET 5 MVC 6 (vNext)에서 ID에 대한 암호 규칙을 어떻게 정의합니까?


ASP.NET 5에서 제공되는 기본 ID 공급자에는 기본적으로 매우 엄격한 암호 규칙이 있으며 소문자, 대문자, 영숫자가 아닌 문자 및 숫자가 필요합니다. 공급자의 암호 요구 사항을 변경하는 방법을 찾고 있습니다.

이전에 ASP.NET 4에서는 이전에 답변 한대로 Web.config XML 파일을 통해 공급자를 구성 할 수있었습니다 . 그러나 ASP.NET 5는 새로운 코드 기반 구성 패턴을 사용하며 ID를 구성하는 방법이 명확하지 않습니다.

내 응용 프로그램의 암호 요구 사항을 어떻게 변경할 수 있습니까?


나는 실제로 이것을 알아 내고, 그것이 제공하는 IdentityOptions를 구성하는 적절한 람다 식으로 AddDefaultIdentity를 제공해야한다는 것이 밝혀졌습니다. 이것은 Startup 클래스 내의 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;
            });
    }
}

업데이트 2 :

위의 내용은 프레임 워크의 베타 1 버전에서 사실이며, 최신 rc1 베타 5에서는 다음과 같이 약간 변경되었습니다.

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();

새 웹 프로젝트를 설정 한 경우 다음으로 Individual User Accounts이동하십시오.

App_Start -> IdentityConfig.cs

여기에서 다음 기본값을 편집 할 수 있습니다.

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

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();

내가하고 싶었던 것은 소문자, 대문자, 숫자 및 특수 기호 그룹 중 2 개 이상의 문자를 포함하도록 암호 규칙을 사용자 지정하는 것이 었습니다 .

이것은 PasswordValidator 옵션을 변경하여 수행 할 수있는 작업이 아닙니다.

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

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

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

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
        // don't forget to include white space in special symbols
        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:

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,
        };
        */

참고URL : https://stackoverflow.com/questions/27831597/how-do-i-define-the-password-rules-for-identity-in-asp-net-5-mvc-6-vnext

반응형