Simon
Simon

Reputation: 736

User.IsInRole() fails when in multiple roles retrieved from Identity Server 4 token

If there is a single role in the token, User.IsInRole() works Claim working (single)

However, if there are multiple roles, then it does not Roles failing

Here is how the roles are added (seems the same as lots of other posts online) code adding roles to context.issueClaims

Here is how the roles are decoded from the claims

Option Claim Actions

This just seems to work for people, and I've read they get the roles back as an array like I get, but it works. So, I assume there is something in the configuration about getting the roles, but I'm out of ideas and hope the great community of SO can help!

UPDATE 1

I amended the line options.ClaimActions.MapUniqueJsonKey( "role", "role", "role" ); to options.ClaimActions.MapJsonKey( "role", "role" );

and now my claims look like:

Roles split into individual items

so the roles are now split from the array, but the IsInRole() still fails to find Administrator (and the others)

Upvotes: 0

Views: 1355

Answers (1)

Simon
Simon

Reputation: 736

The right combination is:

Since the default roleClaimType is http://schemas.microsoft.com/ws/2008/06/identity/claims/role this needs to match what the claim is actually being sent as. In my case, this is just "role". Therefore

options.TokenValidationParameters = new TokenValidationParameters
{
    RoleClaimType = "role",
    NameClaimType = "name"
};

is needed to specify that "role" is the claim to look for. However, that was not sufficient on it's own. The role claims were not being added to the list of claims. This line of code was required:

options.ClaimActions.MapJsonKey( "role", "role" );

and this says for the "role" claim type (param 1) look in the json token and find a json key of "role" (param 2). This is sufficient to now get the roles into the claims list for the user.

In the claims list which I printed on my /permissions page i see

role InstitutionalAdmin
role IDS_Admin
role Administrator

printed out, there are now the three claims listed (not in an array)

and the IsInRole is now behaving too:

Administrator
True
Attendee
False
InstitutionalAdmin
True
ModuleUserAdmin
False
IDS_Admin
True

This is a subset of what was printed out, but the three claim roles are now being set as True in the IsInRole call. Not sure exactly what differs from Update1 but, subject to further testing, it looks good now.

My final points are to firstly thank https://stackoverflow.com/users/5298150/abdusco for engaging and prompting me to look and understand what each param meant. Secondly, I always believe that in pasting code you find on the web is fine, and justified (why reinvent the wheel), BUT please take the time to fully understand what it does and why it is there.

Upvotes: 3

Related Questions