Created
June 26, 2018 09:25
-
-
Save jmcd/5d4c54a3e10b61e3743d47980a0d6c3c to your computer and use it in GitHub Desktop.
Handling multiple role from IdentityServer4 on the client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
When IdentityServer4 returns role in access-token JSON the type of the "role" member value differs depending on how many roles are present. Two cases: | |
1) Single role - the value is a string, e.g. "role": "patient". | |
2) Multiple roles - the value is an array-of-string, e.g. "role": ["patient", "agent"] | |
The AspNetCore framework on the client side does not like the second case, and it assumes a string, giving an error saying that it can't cast from Newtonsoft.Json.Linq.JArray to Newtonsoft.Json.Linq.JToken. | |
You can work around this by checking the type of the role JSON in OpenIdConnectOptions. | |
*/ | |
o.Events.OnUserInformationReceived = context => | |
{ | |
if (context.User.TryGetValue(JwtClaimTypes.Role, out var role)) | |
{ | |
var roleNames = role.Type == JTokenType.Array | |
? role.Select(x => (string)x) | |
: new[] { (string)role }; | |
var claims = roleNames.Select(rn => new Claim(JwtClaimTypes.Role, rn)); | |
var id = context.Principal.Identity as ClaimsIdentity; | |
id?.AddClaims(claims); | |
} | |
return Task.CompletedTask; | |
}; | |
/* | |
This replaces any existing role-claim configuration, e.g. | |
o.ClaimActions.Add(new JsonKeyClaimAction(JwtClaimTypes.Role, JwtClaimTypes.Role, JwtClaimTypes.Role)); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment