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

13,309

Solution 1

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

Solution 2

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.)

Solution 3

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

Solution 4

services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.User.AllowedUserNameCharacters = String.Empty; options.User.RequireUniqueEmail = true; })
            .AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();
Share:
13,309
Babar
Author by

Babar

Updated on July 28, 2022

Comments

  • Babar
    Babar almost 2 years

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

    if (ModelState.IsValid)
    {
        var user = new ApplicationUser 
        {
            UserName = model.Name,
            Email = model.Email,
        };
    

    But when I Enter Name in TextBox like Joe Smith It give me an error that is Invalid UserName. It is not allowing user Name to Accept White space. My Question is how can I modify the builtin User Name to allow space and special characters. I am using ASP.NET Core.

    Thanks in Advance.

  • Babar
    Babar over 6 years
    I just want to store full Name First Name + Last Name in table and It has to a space between them.
  • AJ -
    AJ - over 6 years
    Then as I told you keep username as is and use a new property FullName in ApplicationUser class
  • Babar
    Babar over 6 years
    Ok How can I allow duplicate username? Is this possible?
  • dropoutcoder
    dropoutcoder over 6 years
    @Jaffal: Whitesoace is bad practice because username is handle and it is used in the address bar and Joe%20Smith is ugly. Special characters can make web page behave strange(? querystring, # fragment). That is why we are not using special characters in general. Also special characters are not exactly human friendly and readable. Except _ or -.
  • dropoutcoder
    dropoutcoder over 6 years
    @Babar It is not good idea to have duplicity in usernames. Username is handle and have to be unique.
  • AJ -
    AJ - over 6 years
    @cloudikka that's why I told Babar to keep username as is and use new property call it FullName for the purpose he wants and username will stay as is unique doesn't accept special characters or whitespaces Babar just create new property inside ApplicationUser
  • dropoutcoder
    dropoutcoder over 6 years
    @Jaffal: I just extend your comment! I didnt meant to disagree with you.
  • Babar
    Babar over 6 years
    It is not allowing white space and special characters
  • dropoutcoder
    dropoutcoder over 6 years
    I am reviewing the ASP.NET Identity source code and see nothing that will ban whitespace from usage, if you specify one in the AllowedUserNameCharacters property.
  • Babar
    Babar over 6 years
    I always get that error 'Invalid UserName' either I use space or not. Code is not even working with plain character.
  • dropoutcoder
    dropoutcoder over 6 years
    Without the code it will be hard to find out for anyone.
  • Mog0
    Mog0 almost 6 years
    I found that I needed to support a wide variety of characters as they already existed in customer installs so this worked best for me - It disables the checking on user names.
  • James Rao
    James Rao over 2 years
    this should be marked as answer. it works for me. the AllowedUserNameCharacters should be set with ALL characters we want to allow.