Search code examples
c#asp.net-core-webapi.net-7.0asp.net-core-identity

.NET Core userManager failing CreateAsync on an apostrophe


I seem to be failing on the CreateAsync call for the UserManager in my ASP.NET Core 7 Web API controller.

var user = new AppUser
        {
            DisplayName = "Bob O'Donnell",
            Email = "bob.o'[email protected]",
            UserName = "bob.o'[email protected]"
        };

        var result = await _userManager.CreateAsync(user, registerDTO.Password);

I'm guessing the apostrophe is causing issues?

Here is where I am setting up the UserManager:

services.AddIdentityCore<AppUser>(opt =>
{
    opt.Password.RequireNonAlphanumeric = false;
    opt.SignIn.RequireConfirmedEmail = true;
    opt.Stores.MaxLengthForKeys = 128;
}).AddRoles<IdentityRole>()
  .AddEntityFrameworkStores<DataContext>()
  .AddSignInManager<SignInManager<AppUser>>()
  .AddDefaultTokenProviders();

Do I need to add something to this configuration to allow the apostrophe?


Solution

  • Yes you need to add following code to allow apostrophe.

    opt.User.AllowedUserNameCharacters = "abcd....zABCDE...Z0123456789-._@+'";

    ASP.NET Core Identity uses UserValidator<TUser> to validate user names, and by default it disallow special characters.

    Ensure you validate user input to prevent security risks like SQL injection and XSS attacks when accepting special characters in usernames.