By marone: July 2020 | last update: August 2020
Spring security with Keycloak roles
using OAuth 2.0
Goal
In the previous article, we saw how to use keycloak as a resource server. The spring securityhasAuthority
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.xJava 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 AuthenticationRead 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 onUsers
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.
Select ADMIN and click Add selected.
The roles part in access token looks now like: