By Marone: April 2020
How to secure Spring boot with
keycloak and using roles
Goal
In the previous article we learn how to secure the api with keycloak. Only authenticated users can access the api.Now we will go one step further, the user must belong to a specific role.
Used technologies
Keycloak 8.0.1Java 11
curl 7.65
jq 1.5
Custom the configuration
In line 7 we add
SimpleAuthorityMapper
, by default in Spring Security roles are prefixed with ROLE_, so we do not need to adapt the role names on Keycloak side
The URL /protected will require the authenticated user to be an USER.
The URL /admin will require the authenticated user to be an ADMIN.
Add roles in Keycloak
Press Add Role button
In the new window give name in field
* Role Name
: USER and Save
Repeat the same steps to add role ADMIN
Assign role USER to johndoe
Click on Users in the left menu bar. in the new page click View all users and pick johndoe Select USER and click Add selected. Under Effective Roles you will see the USER roleLet's test
The URL /protected is for user johndoe accessible while hiting /admin causes:
"status":403,"error":"Forbidden","message":"Forbidden"
, because johndoe doesn't have the ADMIN role,
References
The complete code can be found in GitHub