How to customize ASP.NET Identity Core Username to allow special characters and space

后端 未结 6 1393
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 18:16

I have changed my Register Action Method to accept user Name instead of Email.

if (ModelState.IsValid)
{
    var user = new ApplicationUser          


        
6条回答
  •  一整个雨季
    2020-12-20 18:46

    The proposed solution can be tricky if you have an exhaustive list of special characters to whitelist.

    If you want to blacklist instead, disable the whitelist in startup.cs:

     services.AddIdentity(
                    options =>
                    {                        
                        options.User.AllowedUserNameCharacters = string.Empty;
                    })
    

    Then create your custom user validator

     public class UsernameValidator : IUserValidator
    where TUser : User
    {
        public Task ValidateAsync(UserManager manager, TUser user)
        {                
            if (user.UserName.Any(x=>x ==':' || x == ';' || x == ' ' || x == ','))
            {
                return Task.FromResult(IdentityResult.Failed(new IdentityError
                {
                    Code = "InvalidCharactersUsername",
                    Description = "Username can not contain ':', ';', ' ' or ','"
                }));
            }
            return Task.FromResult(IdentityResult.Success);
        }        
    }
    

    Then add it to startup.cs:

     services.AddIdentity(
                    options =>
                    {
                        options.Password = new PasswordOptions
                        {
                            RequiredLength = 8,
                            RequireUppercase = true,
                            RequireNonAlphanumeric = true,
                            RequireDigit = true,
                            RequireLowercase = true
                        };
                        options.User.AllowedUserNameCharacters = string.Empty;
                    }).AddUserValidator>()
    

提交回复
热议问题