1

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?

LDJ
  • 6,896
  • 9
  • 52
  • 87
  • 1
    looks to me like you are being inconsistent and trying to pre-normalize the role name. if IDPPlatform.System.Roles.OrgAdmin is a string constant that would normalize to SYSADMIN you should just use the constant everywhere. methods like _roleManager.FindByNameAsync will normalize it inside the method so you don't need to pre-normalize it. same with _userManager.AddToRoleAsync – Joe Audette Nov 23 '16 at 14:10
  • Sorry, that was a copy/paste error. It does resolve to "SYSADMIN" and the constant is indeed used everywhere, I just replaced it in this example to show what it resolved as that is the string that gets put in the name column in SQL Server. I notice NormalisedName is null though in the DB - is that what it is using to match? – LDJ Nov 24 '16 at 05:58

1 Answers1

3

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.

LDJ
  • 6,896
  • 9
  • 52
  • 87
  • I was having the same issue. Thanks for the workaround. Probably this is exactly how it's supposed to work. – abedon Mar 10 '17 at 02:02