Securing Kotlin REST APIs Using KeyCloak with SpringBoot

Table of Contents
Kotlin Rest APIs security using KeyCloak with springboot

In today’s modern era of software web development, we have a number of cutting-edge technologies claiming to be more proficient than each other in terms of being developer-friendly and having better user experience, But at the same time, there are always challenges in finding better security to these web applications from all the unethical sources. Today, I will briefly discuss securing Kotlin Spring boot applications with the collaborative use of KeyCloak (an open-source identity and access management solution) with SpringBoot.

Quick Introduction to Keycloak

We can say that Keycloak is the standalone tool for identity and access management, which allows us to create a user database with custom roles and groups. Let’s use this information further to authenticate users within our application and secure parts of it based on predefined roles. Since the blog is not about Keycloak, we will not go into details. For deeper information about it and how to configure it refer to their official website.

Kotlin Spring Security Using Keycloak with SpringBoot

In order to use Keycloak with SpringBoot for securing a Kotlin springboot application, we require:

  • Maven/Gradle dependencies
  • Setting up Keycloak on a local machine
  • IDE of your choice for writing code

Maven Dependencies:

For Spring boot Version – 3.1.3

Apart from adding basic Spring security Dependencies below are the prerequisite Keycloak Dependencies.

KeyCloak with SpringBoot Code Screenshot

Keycloak Setup:

  • Download Keycloak sha1 zip file from the website then
  • Unzip the download and from command prompt go to \bin folder.
  • Execute command (for local/dev env): kc.bat start-dev –features=preview and
  • Open http://localhost:8080 to login to Keycloak Console
  • On first access, it will ask to create an Admin user to login.
  • So login with admin user and voila!
  • Now, create a realm from the top left where there is  “master” realm on display.
  • In new realm, create a client with below settings:

           1. Client authentication: ON

           2. Authorization: OFF

           3. Generate client credentials and copy them. 

Congratulations! The basic setup of our Keycloak is complete.

Integrating Keycloak in Kotlin Springboot Application:

We will use Keycloak to create, store and authenticate a user. Later in the Blog, I will discuss Role based authentication using KeyCloak.

First step towards this goal is to set up the KeyCloak configuration in the application.yml file (or properties file).

Below are the basic set of properties necessary to set for the connection of KeyCloak with SpringBoot application

NOTE:- Make sure that Keycloak instance is up and running while you try to run your Kotlin spring boot application

KeyCloak with SpringBoot Code Screenshot

Register User

Let us begin with the coding part and write an API to register the user.

In order to register a user into Keycloak, the minimum information required is: 

  • Username(or alternatively email Address itself)
  • Email Address
  • Password

So, our model class should look something like this, where keyCloakUserId is something returned by Keycloak user registration service as we will see going further.

Code screenshot

Assuming that a basic REST api endpoint can be created, Let’s move directly to the keyCloak service.  the basic KeyCloak configuration private variables using the above .yaml file as below :

Code Screenshot

Creating a KeyCloak Connection Object

Keycloak maven libraries use RestEasyClient to connect to the KeyCloak AUTH Server API endpoint

Code Screenshot

Registering New User

For registering new user in KeyCloak DB instances of UserRepresentation and CredentialRepresentation are created where the user details are set and saved in Keycloak through keycloak RealmResource instance obtained through the Connection Object created in previous step.

After successful user registration in Keycloak, the response object must contain a unique Keycloak User Id as returned by the keycloak API. 

KeyCloak with SpringBoot Code Screenshot

User login/Authentication

The Kotlin login API should accept username and password for authentication. Keycloak exposes its API for user authentication through Authz Client and returns us with a JWT auth token called “access token” which we then can use to authenticate further Kotlin services. Authz client is class that serves as an entry point for clients looking for access to Keycloak Authorization Services. The client tries to obtain server configuration by invoking the UMA Discovery Endpoint, usually available from the server at http(s)://{server}:{port}/auth/realms/{realm}/.well-known/uma-configuration.

Along with the access token, Keycloak gives a “refresh token”, which we can use to regenerate the access token in case the former token expires, and all this is done automatically by the Kotlin microservice without even letting the user know about it and without him having to re-login. In order to use the refresh token when required, we can set it in request cookies and then retrieve and use it when needed (discussed in next steps).

The expiry of these tokens and their management happens through the Keycloak Admin Console (which is out of scope of this article).

KeyCloak with SpringBoot Code Screenshot
Code Screenshot

Response of the above chunk of code is an object of AccessTokenResponse which is OAuth 2.0 Access Token Response json.

Setting refresh-token details in cookies

KeyCloak with SpringBoot Code Screenshot

Enable Spring Security to Use Keycloak Access Token for Authentication APIs

First of all, disable the default spring security setting through the .yaml/properties file (already mentioned in the .yaml file configs shared above)


Spring Security Filter must allow your registration and login API end points and authenticate the rest of the end points.

KeyCloak with SpringBoot Code Screenshot

Getting the new access token using Refresh token

In order to get fresh access token from Keycloak, we need to first validate if the actual access token has expired or not. For this, we need to intercept the Security Filter chain’s authentication by using . addFilterBefore()  method of HttpSecurity class.

Add below line of code after .oauth2ResourceServer{}

Code Screenshot

And adding this method in Security Configuration class. And adding this method in Security Configuration class. keycloakService is the instance of Service class written by you where you write code connecting with Keycloak

Code Screenshot

Now, create a class TokenAuthenticationFilter which implements springboot’s OncePerRequestFilter. Override doFilterInternal() to check access token validity and if expired issue new token using refresh token.

We can use a refresh-token set in cookie in case of expiration to generate new access and refresh tokens. We can not directly modify the request Header of HttpServletRequest inherits ServletRequest interface, implementing only get methods. So, to serve our purpose, we create a custom class which implements HttpServletRequestWrapper and thus, override getHeader() and create a putHeader() method as shown below.

KeyCloak with SpringBoot Code Screenshot
KeyCloak with SpringBoot Code Screenshot

NOTE:- You need to reset the refresh-token with new values in cookies if the access token was regenerated


So, this is how we implement Kotlin REST Api security with the help of Keycloak with SpringBoot.

We need not to store user credentials in our application database as KeyCloak manages that in its inbuilt DB. We just need to store user id generated by Keycloak during user registration in order to map User in Keycloak with other User data stored in application Database.

We can also do Role based authorization of APIs with the help of Keycloak and Spring Security, which we will discuss in detail in the upcoming blog.

Happy Coding!

Share this blog

What do you think?

Contact Us Today for
Inquiries & Assistance

We are happy to answer your queries, propose solution to your technology requirements & help your organization navigate its next.
Your benefits:
What happens next?
We’ll promptly review your inquiry and respond
Our team will guide you through solutions

We will share you the proposal & kick off post your approval

Schedule a Free Consultation

Related articles