2
votes

This seems like a simple exercise, but I can’t figure out why this is different?

User.HasClaim(System.Security.Claims.ClaimTypes.Role, “AdminRole”)

true

User.IsInRole(“AdminRole”)

false

The above should evaluate to the same result, but it isn't. I'm just using cookies authentication and loading the claims into a claims principle.

This becomes a problem when I try to use the Authorize attribute like [Authorize(Role="AdminRole")], which returns false while having the what seems to be the right role claim.

1
Can you demonstrate where you set the value of the claim?Kirk Larkin
Claims are only refreshed after re-auth. If you update a claim, then you should sign the user user out and sign them back in again.Chris Pratt
The claims are set and then the users are signed in via await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal); Also, since HasClaims was able to return true, meaning the claim itself is set correctly, so IsInRole should return true as well, right? Both HasClaim and IsInRole are evaluated at the same time, but different result.Y.Z.
can you try using TokenValidationParamaters option in your config to map it to the roles claim like options.TokenValidationParameters = new TokenValidationParameters{RoleClaimType = System.Security.Claims.ClaimTypes.Role }Muqeet Khan
Also looking at your Authentication options & code for AddClaims will be helpful.Muqeet Khan

1 Answers

0
votes

If you got here looking for the proper syntax for checking roles using an attribute in ASP.net core 2 or above, the answer is almost like is given in the above deleted answer:

[Authorize(Roles = "Admin")]