Integrating Keycloak’s Access Management Solution with a Spring Boot Application

Overview

In this article, we’ll be covering the following topics :

  • Installing and setting up a keycloak server in your machine
  • Keycloak integration with a Spring Boot application
  • Using Spring Security

What is Keycloak?

Keycloak is an open source identity and access management solution which mainly aims at applications and services.

Users can authenticate with Keycloak rather than individual applications.

So, the applications don’t have to deal with login forms, authenticating users and storing users. Once logged-in to Keycloak, users don’t have to login again to access different applications.

Same thing is applicable to sign-out. Keycloak offers everything a sophisticated user management tool needs – without having to log on repeatedly with every login and into every system-as well as system security, social logins, support for mobile apps and integration into other solutions.

In simple terms, Keycloak serves as a solution to manage authentication and authorization features. For more details, you can check out the official documentation available in the official website.

Installing and setting up Keycloak

Keycloak can be used as a standalone application or with Docker/Kubernetes. For this article we will use the Standalone server distribution.

  1. Download the Standalone server distribution here. The latest version as of now is 11.0.0.

If you’re using linux, make sure to download the tar.gz version.

  1. Once downloaded, extract the folder and start Keycloak from the terminal.

cd keycloak-11.0.0/
cd bin/
./standalone.sh -Djboss.socket.binding.port-offset=100

  1. Now with Keycloak up and running, open up a browser and visit http://localhost:8180 to create an admin login.
  1. After setting up an username (e.g. codefiction) and a password, click Create and you should expect a “User created” message to assert everything worked.
  2. Go to the Administrative Console and enter the admin credentials you just registered.

Getting started with Keycloak

After logging in, a default Master realm should show up.

Navigate to the upper left corner to discover the “Add realm” button and add a new realm called Spring-Boot-Keycloak.

After creating a new realm, we should be redirected to our Spring-Boot-Keycloak realm configuration where all the following operations will be executed.

Creating a new client

Keycloak comes with built-in clients that you can check by navigating to the Clients page.

To create a client for our application, we can click the “Create” button on the upper right corner of the clients table.

Set a client id for identification and click “Save”.

In the next screen, we can leave all the default configuration intact except for the “Valid Redirect URIs field” where we need to specify the application URL that will be used in this client for authentication.

Setting up a Role and a User

Since Keycloak uses Role-Based access, all users must have a defined role.

Navigate to the “Roles” page and add a role by clicking the “Add Role” button in the upper right corner of the roles table.

To create a user role, specify a name and a description.

Now that we have a user role, we may go to the “Users” page and add some data to it.

Click the “Add user” button, specify the username, first name and last name of an user and click “Save” to display a page with the details envolved.

To set a password to the defined used, go to the “Credentials” tab next to “Attributes” and “Role Mappings”.

Now to assign the user role to our user_one, navigate to the “Role Mappings” tab, select the user role in the “Available Roles” section and move it to the “Assigned Roles”.

How to generate an Access Token with Keycloak’s API

To create our login page, we’ll use Keycloak’s REST API to generate and refresh access tokens through the following steps :

  1. Acquire an access token by sending a POST request to :

http://localhost:8180/auth/realms/master/protocol/openid-connect/token

  1. Specify as the POST request body :

{
    ‘client_id’: ‘your_client_id’,
‘username’: ‘your_username’,
‘password’: ‘your_password’,
‘grant_type’: ‘password’
}

  1. Place the access token in the Authorization header :

headers: {
    ‘Authorization’: ‘Bearer’ + access_token
}

  1. Send a POST request to the same URL as before to refresh the access token when it expires, make sure to include in its body the refresh token instead of the username and password :

{
    ‘client_id’: ‘your_client_id’,
‘refresh_token’: refresh_token_from_previous_request,
‘grant_type’: ‘refresh_token’
}

Integration with a Spring Boot application

Since the Keycloak Spring Boot adapter is fully integrated with Spring Boot’s auto-configuration, all we need to do is add the Keybloak Spring Boot starter to our project.

Make sure to include in your maven pom.xml file :

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
</dependency>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.keycloak.bom</groupId>
            <artifactId>keycloak-adapter-bom</artifactId>
            <version>10.0.2</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

With this configuration, we’ll enable the following embedded containers when using Spring Boot Keycloak Starter :

  • Tomcat
  • Undertow
  • Jetty

Creating our Web Page

For our web page, we’ll use Thymeleaf, a modern server-side Java template engine for both web and standalone environments.

We’ll have three pages to handle all requests :

  • users.html : page with access restricted to only authenticated users with the user role
  • layout.html : simple layout page with two fragments used for both the external and users page
  • external.html : a facing web page for public access

Creating our Spring Boot application

Our application will consist of five main files (four classes and one interface) :

  • CodefictionDemoProjectApplication : Main class, used only to bootstrap and run the application with Spring Boot
  • Config : Configuration class with all the specifications and details regarding Keycloak
  • User : Simple class to create the user entity and set its getters and setters
  • UserDAO : Interface that extends CrudRepository to handle DB operations on top of the user entity
  • WebController : Used to map the internal and external URLs to the appropriate Thymeleaf templates

We’re also using as dependencies :

  • Lombok
  • Spring Security
  • Spring Web
  • Spring Data JPA
  • Thymeleaf and Keycloak (as we previously mentioned)

For the source code, you can click here.

Keycloak Configuration

In the application.properties file, we enter the basic configuration for our Keycloak integration :

// Set here the path specified in keycloak.auth-server-url
keycloak.auth-server-url=http://localhost:8180/auth
// Set here your realm name
keycloak.realm=Spring-Boot-Keycloak
// Set here the client named in the admin console
keycloak.resource=login-application
keycloak.public-client=true

As security constraints (not needed because we’re using Keycloak Spring Security Adapter) :

keycloak.security-constraints[0].authRoles[0]=user
keycloak.security-constraints[0].securityCollections[0].patterns[0]=/customers/*

These ensure that all requests sent to /users/* will only be authorized if it’s requested by someone with the user role.

As additional configuration, we set the following to populate our controller’s Principal with a proper user :

keycloak.principal-attribute=preferred_username

Running the application

To test our application, start it through the IDE and visit http://localhost:8081.

Once we log in as the user we defined previously, Keycloak verifies our authorization and redirects us to the users files page with our example data.

Endnotes

In the next posts we will cover using oauth2, registering and logging in using Google, Github, etc.

All source code from this article is available here in our GitHub page, feel free leave a comment or suggestion below for what you’d like for us to cover in the next article.

About the author

Website | + Posts

Software Consultant with more than 11 years experience, most of that in Finance area. I love building things and see them running and making a difference.

Specialised in Golang (2 years), Java (11 years), Javascript, React and Angular (1 year), PHP (2 years), project management and delivery leading (2 years), mentoring and coaching (1 year).

Website | + Posts

Electrical engineering student from Brazil passionate about learning and teaching people.

Had some professional and academic engineering experiences, now my focus is on studying and developing software as a full time job.

Leave a Reply

Your email address will not be published. Required fields are marked *