'Microsoft.AspNetCore.Identity.IdentityError: "InvalidUserName"

I did default Megration with User model, added only my two custom properties. EF created standard flow of tables.

enter image description here

And my AspNetUsers table

enter image description here

As you can see UserName can be null.

My User Model

public class User : IdentityUser
{
    public string FullName { get; set; }
    public string CreateAt { get; set; }
    public User()
    {
        this.CreateAt = Convert.ToString(DateTime.Now);
    }
}

And when I create user, I have exeption

enter image description here

But I didnt make any validation or rules for UserName. My startup configuration for ApplicationDBContext

services.AddIdentityCore<User>(opts =>
        {
            opts.Password.RequiredLength = 5;
            opts.Password.RequireNonAlphanumeric = false;
            opts.Password.RequireLowercase = true;
            opts.Password.RequireUppercase = true;
            opts.Password.RequireDigit = true; 
            opts.User.AllowedUserNameCharacters = null;
        }).AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDBContext>()
        .AddDefaultTokenProviders();

opts.User.AllowedUserNameCharacters = null; Didn't help me. What I do wrong?



Solution 1:[1]

You're trying to set your username to an empty string. Looking at the validation method within a GitHub repository of Microsoft.AspNetCore.Identity, there seems to be no way for you to allow null or an empty string as a valid username. Setting AllowedUserNameCharacters to null simply means that you're not checking for the whitelisted characters, which is also the default behavior, but pre-validation for IsNullOrWhiteSpace remains intact.

Check the comment within this code snapshot from the official repository:

private async Task ValidateUserName(UserManager<TUser> manager, TUser user, ICollection<IdentityError> errors)
{
    var userName = await manager.GetUserNameAsync(user);
    if (string.IsNullOrWhiteSpace(userName)) // <-- There is no way around this.
    {
        errors.Add(Describer.InvalidUserName(userName));
    }
    else if (!string.IsNullOrEmpty(manager.Options.User.AllowedUserNameCharacters) &&
        userName.Any(c => !manager.Options.User.AllowedUserNameCharacters.Contains(c)))
    {
        errors.Add(Describer.InvalidUserName(userName));
    }
    else
    {
        var owner = await manager.FindByNameAsync(userName);
        if (owner != null &&
            !string.Equals(await manager.GetUserIdAsync(owner), await manager.GetUserIdAsync(user)))
        {
            errors.Add(Describer.DuplicateUserName(userName));
        }
    }
}

Solution 2:[2]

builder.Services.Configure<IdentityOptions>(options =>
{
  // Paswoord instellingen
  options.Password.RequireDigit = true;
  options.Password.RequireLowercase = true;
  options.Password.RequireNonAlphanumeric = true;
  options.Password.RequireUppercase = true;
  options.Password.RequiredLength = 6;
  options.Password.RequiredUniqueChars = 1;

  // Gebruiker instellingen
  options.User.RequireUniqueEmail = true;
  options.User.AllowedUserNameCharacters =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; // here is the issue

  // Lockout instellingen
  options.Lockout = new LockoutOptions
  {
    AllowedForNewUsers = true,
    DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5),
    MaxFailedAccessAttempts = 5
  };
});

Check the line where i've written the text that

here is the issue

The characters you specify here are what the IUsersValidator uses for validating usernames. In my own case I had user names with @ and . characters - I had to add them here. Otherwise you do not get exceptions from this AddUserToRoleAsync() or AddUserToRole() with an invalid username, you only get a result with a status and an error message.

Please configure the allowed username characters and you are good to go

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 msmolcic
Solution 2 Edward Iga Kigongo