Search code examples
asp.net-coreasp.net-identity-3

AddToRoleAsync fails to find Role


I have a small test app using Asp.net Core Identity. In the startup I check that certain system roles are in place:

if(await _roleManager.FindByNameAsync(“SYSADMIN”) == null)
{
  _context.Roles.Add(new IdentityRole(“SYSADMIN”));
  await _context.SaveChangesAsync();
}

Then I check and create a system admin account if it doesn’t exist:

var result = await _userManager.CreateAsync(adminUser, config["AdminPassword"]);

I then try and add that user to the SYSADMIN role:

if (result == IdentityResult.Success)
{                  
  await _userManager.AddToRoleAsync(adminUser, “SYSADMIN”);
}

but get an error that the role does not exist. I can, however, see the role with the above name in AspNetRoles and when I run the app for a second time, it doesn’t go into the _context.Roles.Add() section as _roleManager.FindByNameAsync returns the role.

Has anyone seen this behaviour before or know whats going on as to why its failing?

edit I notice NormalisedName is null though in the DB - is that what it is using to match?


Solution

  • So this looks like a bug to me. If you use the constructor that takes only a string, it populates the name, but not the normalised name. It would appear that the normalised name is matched on in AddToRoleAsync so it'll never work.

    I needed to use the following to force the NormalizedName to be populated:

    _context.Roles.Add(new IdentityRole("SYSADMIN")
    {
      NormalizedName = "SYSADMIN"
    });
    

    And its now working. I'll file a bug with the team and hopefully it'll get fixed.