I add the role administrators
to user claims after authentication with an IClaimsTransformer
impelimentation like this:
(principal.Identity as ClaimsIdentity).AddClaim(new Claim(ClaimTypes.Role, "Administrators"));
But when i call User.IsInRole("Administrators")
in my Razor view it return false.
I'm doing something similar in an API-based solution, but I set the role claim when I create the user, instead of in a transformer.
After looking at the User.IsInRole()
documentation it appears that this method is designed to pull from a cache first.
IsInRole first checks the IsRoleListCached property to determine whether a cached list of role names for the current user is available. If the IsRoleListCached property is true, the cached list is checked for the specified role. If the IsInRole method finds the specified role in the cached list, it returns true. If IsInRole does not find the specified role, it calls the GetRolesForUser method of the default Provider instance to determine whether the user name is associated with a role from the data source for the configured ApplicationName value.
I suspect since ClaimTypes.Role
is a common claim and not a custom domain-specific claim (which I believe is the use-case for a ClaimsTransformer), the application is using a default, cached, pre-transform value.
Much of this is speculation, though. You may try setting the claim when you create the user. I do it using the UserManager class.
var claimsResult = await _userManager.AddClaimAsync(applicationUser, new Claim(ClaimsIdentity.DefaultRoleClaimType, "Administrator"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With