Having a few minor issues with role based authorization with dotnet core 2.2.3 and Keycloak 4.5.0.
In Keycloak, I've defined a role of 'tester' and a client role 'developer' with appropriate role mappings for an 'admin' user. After authenticating to Keycloak; if I look at the JWT in jwt.io, I can see the following:
{
"realm_access": {
"roles": [
"tester"
]
},
"resource_access": {
"template": {
"roles": [
"developer"
]
},
...
},
...
}
In .NET core, I've tried a bunch of things such as adding [Authorize(Roles = "tester")]
or [Authorize(Roles = "developer")]
to my controller method as well as using a policy based authorization where I check context.User.IsInRole("tester")
inside my AuthorizationHandler<TRequirement>
implementation.
If I set some breakpoints in the auth handler. When it gets hit, I can see the 'tester' and 'developer' roles listed as items under the context.user.Claims
IEnumerable as follows.
{realm_access: {"roles":["tester"]}}
{resource_access: {"template":{"roles":["developer"]}}}
So I should be able to successfully do the authorization in the auth handler by verifying the values for realm_access
and resource_access
in the context.user.Claims
collection, but this would require me to deserialize the claim values, which just seem to be JSON strings.
I'm thinking there has to be better way, or I'm not doing something quite right.
"AspNetCore.Authorization" expects roles in a claim (field) named "roles". And this claim must be an array of string (multivalued). You need to make some configuration on Keycloak side.
The 1st alternative:
You can change the existing role path.
Go to your Keycloak Admin Console > Client Scopes > roles > Mappers > client roles
The 2nd alternative:
If you don't want to touch the existing path, you can create a new Mapper to show the same roles at the root as well.
Go to your Keycloak Admin Console > Client Scopes > roles > Mappers > create