By Marone: April 2020
GoalIn 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 technologiesKeycloak 8.0.1
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 johndoeClick 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 role
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,
The complete code can be found in GitHub