By marone: July 2020 | last update: August 2020

Spring security with Keycloak roles
using OAuth 2.0


In the previous article, we saw how to use keycloak as a resource server. The spring security hasAuthority was internally mapped from jwt scopes. It was fine but if someone is very familiar with keycloak roles, it will be difficult for them to work with scopes. Or some authorization servers don't support scopes. So we need a kind of mapping between Spring security and keycloak roles.

Used technologies

Keycloak 8.x
Java 11
curl 7.66
Maven 3.x
jq 1.5

Jwt converter

At first, we need a JWT converter, which will extract the roles from access token and returns an Authentication
Read the roles from JWT. The roles are part of the claim realm_access.
Each role will be converted to a SimpleGrantedAuthority object.
To make the mapping more easer the prefix was added ROLE_.

Adapt the configuration

We use now hasRole instead of hasAuthority.
We use the custom OAuth2ResourceServerConfigurer which uses the JWT converter.

Keycloak roles in access token

Let's test

The Resource Server expected a role with ADMIN as value.

Change roles mappings

To assign the ADMIN role to the user click on Users in the left menu bar. Now on the right side click View all users and pick up johndoe, a new page will appear. Go to the Roles Mappings tab.
OAuth2 keycloak roles Select ADMIN and click Add selected.
The roles part in access token looks now like:

Let's test again