Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The User.IsInRole("Administrators") with IClaimsTransformer always false

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.

like image 936
Mike Anderson Avatar asked Apr 22 '16 09:04

Mike Anderson


1 Answers

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"));
like image 198
Garrett Clyde Avatar answered Nov 04 '22 07:11

Garrett Clyde