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

后端 未结 6 1391
没有蜡笔的小新
没有蜡笔的小新 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:35
    services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.AllowedUserNameCharacters = String.Empty; options.User.RequireUniqueEmail = true; })
                .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
    
    0 讨论(0)
  • 2020-12-20 18:39

    UserName should not allow special characters or white spaces, I don't think that there is any website will allow you to do that, you can use FirstName and Last name to get an info like "Joe Smith".

    0 讨论(0)
  • 2020-12-20 18:43

    You can set user validation rules configuring identity with options in your Startup.cs.

    services.AddIdentity<ApplicationUser, IdentityRole>(options => {
        options.User.AllowedUserNameCharacters = "allowed characters here";
        options.User.RequireUniqueEmail = true/false;
    });
    

    Related resources:

    Configure Identity

    0 讨论(0)
  • 2020-12-20 18:44

    As mentioned by @Jaffal the UserName should not allow special characters or white spaces. It should be considered as a unique user identifier (a.k.a. nickname or email). To get nicely displayed user name you might want to introduce a new property.

    E.g. add a new property called Name or in some other implementation may be two fields GivenName and FamilyName. And ask user to fill in her name to these fields.

    To extend the database with the extra field(s) your migration can be:

    public partial class ApplicationUserNamePropertyAdded : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "Name",
                table: "AspNetUsers",
                nullable: true);
        }
    
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Name",
                table: "AspNetUsers");
        }
    }
    

    In your code when you Register a new user using ASP.NET Identity classes you will have a code line like:

    var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Name = model.Name };
    

    Basically, the user's UserName will always be the same as Email and another Name property will be used for displaying purposes.

    0 讨论(0)
  • 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<User, Role>(
                    options =>
                    {                        
                        options.User.AllowedUserNameCharacters = string.Empty;
                    })
    

    Then create your custom user validator

     public class UsernameValidator<TUser> : IUserValidator<TUser>
    where TUser : User
    {
        public Task<IdentityResult> ValidateAsync(UserManager<TUser> 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<User, Role>(
                    options =>
                    {
                        options.Password = new PasswordOptions
                        {
                            RequiredLength = 8,
                            RequireUppercase = true,
                            RequireNonAlphanumeric = true,
                            RequireDigit = true,
                            RequireLowercase = true
                        };
                        options.User.AllowedUserNameCharacters = string.Empty;
                    }).AddUserValidator<UsernameValidator<User>>()
    
    0 讨论(0)
  • 2020-12-20 18:49

    So cloudikka's answer had it right. I'll just add explicitly (cloudikka's link explained it as well) that you need to list ALL the characters you want to allow (not just the whitespace or special characters), like this:

    services.AddIdentity<ApplicationUser, IdentityRole>(options => {
        options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+/ ";
    });
    

    and NOT this options.User.AllowedUserNameCharacters = " "; which means 'only whitespace characters allowed'. (I reckon this was Babar's problem.)

    0 讨论(0)
提交回复
热议问题