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.
Realm-level roles are a global namespace to define your roles. You can see the list of built-in and created roles by clicking the Roles left menu item. To create a role, click Add Role on this page, enter in the name and description of the role, and click Save.
in our frontend - send username and password to KC “token” endpoint and get an authorization code. pass this code to our Backend server. Backend send this code + secret to the KC to get a valid Access token (and refresh token) BE send the access token back to the FE.
"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
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