codememo

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

tipmemo 2023. 6. 17. 09:25
반응형

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

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

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

응용 프로그램의 암호 요구 사항을 변경하려면 어떻게 해야 합니까?

실제로 이 문제를 해결했습니다. AddDefaultIdentity에서 제공하는 IdentityOptions를 구성하는 적절한 람다 식을 제공해야 합니다.이 작업은 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,
 };

대신에 IdentityValidator를 확장하여 사용자 정의 Validator를 만들었습니다.

먼저 확장명 폴더에 새 파일 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(
                $"Password should be at least {RequiredLength} characters"));
        }

        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 and special symbols"));
        }

        return Task.FromResult(IdentityResult.Success);
    }
}

그런 다음 IdentityConfig.cs 으로 이동하여 Create 메서드로 초기화합니다.

manager.PasswordValidator = new CustomPasswordValidator(8 /*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

반응형