ASP.NET Core (API, Blazor, MVC) + Keycloak — Part 5

Luy Lucas
2 min readJan 28, 2024

--

This part is about loading roles in the jwt token

Part 1;

Part 2;

Part 3;

Part 4;

Now that we have all clients configured, there is a bonus.

Since we used a public client in Keycloak, it’s not possible to use authorization services to have fine-grained authorization.

As a result, we only have groups and roles to use (RBAC).

To do this, we open the admin UI, select the client that was created, and in the ‘Client Scope’ tab, we select the ‘<clientid>-dedicated’ scope:

Click in Add Mapper > By Configuration:

Select the ‘User Client Role’ option:

Set its configuration like this:

Now, every created token will contain the role attribute:

Click on Evalute tab, on side of Setup tab, bellow the Client Scopes tab

The API app just has the role name configured so we don’t need to set it.

In the MVC app, we have to input this in the OpenIdConnect options:

And in Blazor too:

That’s it. Now, all roles of an authenticated user will be loaded and you can use in Authorize attribute to check user permissions.

All this code is in my example repository.

--

--