no

Role Based Access Control in Spring Boot with Keycloak

I. Introduction The purpose of this tutorial is to restrict the menu access depending on the users' roles. This is a companion t...

I. Introduction

The purpose of this tutorial is to restrict the menu access depending on the users' roles.

This is a companion tutorial of my blog entry available at https://czetsuya-tech.blogspot.com/2020/01/secure-spring-boot-2-rest-api-with-keycloak-8.html. This tutorial will help you set up a Spring REST project and Keycloak realm.

II. Importing the Spring REST Project

Import the project from Github at https://github.com/czetsuya/spring-keycloak-rbac.

III. Importing the Keycloak Realm

1.) To start Keycloak run: 
>standalone.bat -Djboss.socket.binding.port-offset=1 -Dkeycloak.profile.feature.upload_scripts=enabled

2.) Navigate to http://localhost:8081/auth and set up your admin account or login if you already have.

3.) Hover the Master link and click the Add Realm button.

4.) Import the realm config from the config folder of the downloaded project. There are 2 files 1 is the realm configuration and the other is for the users.

5.) Import the realm file. It should have the following configuration.

realm name=balambgarden
client (confidential)=sso-client
client (bearer)=api-services

6.) Import the user file using the Import menu in the left panel. The following users and roles will be created.

Role=PROMOTER, User=sarah / kerrigan
Role=SUPERVISOR, User=jim / raynor

IV. The Spring REST Project

We have the Menu class, where we save a menu entry in the database. I have already, created dummy data in data.xml.

I have created a class CurrentUserProvider, where the current logged user is produced.

And the MenuService, fetch and order the menus based on the users' roles.
Let's take a look at the MenuController that returns a list of menus depending on the role of the logged user.

V. Testing

Import the spring-boot-keycloak-rbac postman collection that I have uploaded in the config folder of the project.

Run each of the tests to get an idea of what is happening. But basically, the "get menu by role" test will return a list of menus depending on the logged user. See the different responses between sarah and jim account.

Related

coding 7016670562266973216

Post a Comment Default Comments

item