ASP.NET Core Identity Role, Claim and User

trinvh picture trinvh · Feb 3, 2017 · Viewed 8.7k times · Source

I am an ASP.NET Core beginner. I'm stuck in role, claim and user relationship.

I have a user Ben, user belongs to Admin role. Admin role has claims view-page and edit-page in database.

But I can't get claims and roles to be belonging to that user:

(Please see comment in code)

var user = await _userManager.FindByNameAsync(applicationUser.UserName);
if(user != null) {
    var userClaims = await _userManager.GetClaimsAsync(user); // empty, WHY ?
    var userRoles = await _userManager.GetRolesAsync(user); // ['admin']
    var adminRole = DbContext.Roles.FirstOrDefault(x => x.Name == "Admin");
    IList<Claim> adminClaims;
    if(adminRole != null)
    {
        adminClaims = await _roleManager.GetClaimsAsync(adminRole);
        // correct => ['view-page', 'edit-page']
    }
    }
}

In my mind, I understand when a user is a member of a role, he inherit that role's claims.

Default ASP.NET Identity have 5 tables:

  • Users.
  • Roles.
  • UserRoles - A user can have many roles.
  • RoleClaims - A role can have many claims.
  • UserClaims - A user can have many claims.

Do i think correct ? Why userManager.GetClaimsAsync(user) returns empty claims ?

Any suggestion?

Answer

tmg picture tmg · Feb 3, 2017

Why userManager.GetClaimsAsync(user) returns empty claims ?

Because UserManager.GetClaimsAsync(user) queries the UserClaims table. Same for RoleManager.GetClaimsAsync(role) queries the RoleClaims table.

But by design in ASP.NET Identity Core when a user is a member of a role, they automatically inherit the role's claims. You can check the ClaimsPrincipal, for example inside a controller action:

var claims = User.Claims.ToList();

You can see the code in UserClaimsPrincipalFactory.cs that creates a ClaimsPrincipal from an user.