Integrating Keycloak 4 with Spring Boot 2 Microservices

Keycloak 4.0.0.Final was officially released early this week with a lot of new and awesome features, including support for Spring Boot 2. In this short article, I am going to show how to secure Spring Boot 2 application with the new version of Keycloak. The source code of the project can be found on GitHub.

Keycloak Setup

A proper Docker setup for starting Keycloak is provided.

Executing the following command sets up Keycloak and the necessary PostgreSQL database.

docker-compose -f keycloak/docker-compose.yml up

It also imports a realm with the name "PersonRealm", a client with the identifier "persons-app" and an initial user. Keycloak can be accessed on http://localhost:8081/auth/, whereas the credentials of the admin are admin:password.

The Spring Boot Application

In order to use the provided adapter for Spring Boot the following dependency must be added to the project (note the number 2 in the Id of the artefact):

The following configuration is necessary for the adapter. It mainly tells Spring Boot the URL of Keycloak, the used realm and the proper identifier of the client.

The example application is very simple. The following endpoints are provided, whereas /persons is protected and can only be accessed by users having the role user.

Finally, Spring Security is enabled and properly configured. First Keycloak needs to be registered as an authentication provider. Spring Boot wants roles of users to be prefixed with ROLES_, which is done by the SimpleAuthorityMapper. An appropriate strategy for session management is configured. The last configuration protects the endpoint "/persons", which can be accessed only by users with the role user.

The Spring Boot application is started via:

mvn package spring-boot:run

After the start-up phase, the application can be accessed on http://localhost:8080/. Clicking on All Persons opens the login screen of Keycloak. The previously imported user has the credentials username:password and the role user. A successful log in shows the protected list of customers.

Johannes Innerbichler

Written by

I studied Computer Engineering and became a freelancer in the area of cloud applications, cloud security and data analytics. www.johannesinnerbichler.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade