OAuth2 and OpenID Authentication with Keycloak and Spring Security (Spring Boot 3 and Java 17): Practical Guide — Part 1

Adnene Hamdouni
12 min readApr 9, 2024

--

Introduction

In today’s landscape of developing secure applications, implementing a robust authentication solution is an essential foundation.

This article will explore setting up robust authentication using OAuth2 and OpenID with Keycloak and Spring Security.

The aim is to provide a practical guide, including the setup of the development environment, to enable you to test authentication requests via a Postman collection.

In this first part, we will focus on one of the most crucial steps in securing an application: configuring Keycloak using OAuth2 and OpenID Connect (OIDC).

Then, we will detail the installation and initial configuration of Keycloak.

This foundation will serve as a starting point for the second part of the article, where we will see how to use Keycloak to secure a Spring Boot application through authentication requests tested with Postman.

Prerequisites

  • Java JDK 17 or higher
  • Spring Boot 3.1.0.RELEASE or higher
  • Maven 3.6 or higher
  • Keycloak 12.0.4 or higher
  • Postman to test authentication requests

Development Environment Setup

1. Java JDK 17

Ensure Java JDK 17 is installed on your machine. You can download the JDK from Oracle’s official website or adopt an OpenJDK distribution.

To verify your installation, open a terminal and type:

java -version

2. IntelliJ IDEA

Download and install IntelliJ IDEA from the official site. The Community version is free and sufficient for this project.

Docker Installation and Configuration

To ensure a successful implementation of OAuth2 and OpenID authentication with Keycloak and Spring Security, it is crucial to start by setting up a Docker environment.

Docker is a containerization platform that allows encapsulating your application and its dependencies in an isolated container, ensuring the application runs uniformly in any development, testing, or production environment.

1. Why Docker?

  • Isolation : Each container operates in isolation, reducing conflicts between applications.
  • Portability : Containers can be deployed on any system that supports Docker, facilitating deployment and scaling.
  • Reproducibility : Development, testing, and production environments are identical, reducing the “it works on my machine” issues.

2. Docker Installation

The Docker installation varies depending on the operating system:

-> On Windows

  • Download Docker Desktop: Visit Docker Hub and download Docker Desktop for Windows.
  • Installation: Run the installation file and follow the on-screen instructions. Restart your computer if necessary.
  • Verification: Open a terminal and type the following command to verify the installation :
docker --version

-> On Mac

  • Download Docker Desktop: Visit Docker Hub and download Docker Desktop for Mac.
  • Installation: Open the .dmg file and drag the Docker icon to the Applications folder.
  • Verification: Open a terminal and check the installation with :
docker --version

-> On Linux

  • System Update :
sudo apt-get update

Installation of Prerequisites :

sudo apt-get install apt-transport-https ca-certificates curl software-properties-common

Adding Docker Repository :

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

4. Docker Installation :

sudo apt-get update && sudo apt-get install docker-ce

5. Verification of Docker Version :

docker --version

Testing Docker :

To confirm that Docker is installed and functioning correctly, execute :

docker run hello-world

This command downloads a test image and runs a container that displays a welcome message. If you see this message, it means Docker is correctly installed and configured on your machine.

HelloWorld sample

Having Docker installed and configured correctly is the first crucial step for deploying containerized applications. This prepares you for the installation of Keycloak in a Dockerized environment, making the management of authentication and authorization in your Spring Boot applications easier.

Keycloak with OAuth2 and OpenID

Keycloak is an open-source identity server that offers authentication and authorization functionalities, making it easier to secure web applications and services. Using OAuth2 and OpenID Connect (OIDC), Keycloak allows for robust and flexible user access management.

1. What is Keycloak ?

Keycloak is designed to be security-centric with ease of deployment. It allows developers to easily integrate authentication features into their applications without managing the complex aspects of security.

2. What is OAuth 2.0 ?

OAuth 2.0 is an authorization framework that allows an authenticated user to grant access to third parties via tokens. A token is typically limited to certain scopes with a limited lifespan, making it a secure alternative to user credentials.

OAuth 2.0 includes four main components:

  • Resource Owner: The end-user or system owning a protected resource or data.
  • Resource Server: The service exposing a protected resource, typically through an HTTP-based API.
  • Client: Calls the protected resource on behalf of the resource owner.
  • Authorization Server: Issues an OAuth 2.0 token and delivers it to the client after authenticating the resource owner.

OAuth 2.0 is a protocol with standard flows, but we are particularly interested here in the authorization server component.

3. OpenID Connect

OAuth 2.0 is an authorization framework that allows an authenticated user to grant access to third parties via tokens. A token is typically limited to certain scopes with a limited lifespan, making it a secure alternative to user credentials.

OAuth 2.0 includes four main components:

  • Resource Owner: The end-user or system owning a protected resource or data.
  • Resource Server: The service exposing a protected resource, typically through an HTTP-based API.
  • Client: Calls the protected resource on behalf of the resource owner.
  • Authorization Server: Issues an OAuth 2.0 token and delivers it to the client after authenticating the resource owner.

OAuth 2.0 is a protocol with standard flows, but we are particularly interested here in the authorization server component.

4. Keycloak as Authorization Server

JBoss developed Keycloak as an open-source identity and access management solution based on Java. Besides supporting OAuth 2.0 and OIDC, it also offers features like identity brokering, user federation, and SSO (Single Sign-On).

We can use Keycloak as a standalone server with an administration console or integrate it into a Spring application. Once our Keycloak is operational in one of these ways, we can test the endpoints.

5. Keycloak Endpoints

Keycloak exposes a variety of REST endpoints for OAuth 2.0 flows. To use these endpoints with Postman, we will start by creating an environment called “Keycloak.” Then, we will add some key/value entries for the Keycloak authorization server URL, realm, OAuth 2.0 client identifier, and client password.

Keycloak Architecture with OAuth2 and OpenID

Consider a web application scenario where a user wants to access protected resources:

  • The user requests access to the protected resource via the client application.
  • The application redirects the user to Keycloak for authentication.
  • Once authenticated, Keycloak returns an access token (and possibly an ID token for OIDC) to the client application.
  • The client application uses the token to access protected resources on the resource server.
Keycloak Architecture

Keycloak Installation and Configuration

To integrate authentication and authorization into our applications using Keycloak with OAuth2 and OpenID, we must first configure Keycloak. An effective and isolated manner is through the use of Docker Compose, which allows us to deploy Keycloak in a Docker container.

1. Benefits of Docker Compose

  • Simplicity: Docker Compose makes it easy to start multiple Docker containers as a single service.
  • Configuration via Code: All configuration is managed through a YAML file, making deployment reproducible and easy to version.
  • Isolation: Each service runs in its own container, ensuring isolation and security between services.

2. Configuring Keycloak :

Begin by installing and launching Keycloak. Then, create a Realm and a client. Note the client ID and secret as they will be used in the Spring Boot configuration.

Step 1 : Creating the Docker Compose File

  • Create a folder for your Keycloak project:
mkdir keycloak_project && cd keycloak_project
  • Create a docker-compose.yml file: This file will contain the necessary configuration to run Keycloak.
version: '3'

volumes:
postgres_data:
driver: local

services:
postgres:
image: postgres
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: password
keycloak:
image: quay.io/keycloak/keycloak:legacy
environment:
DB_VENDOR: POSTGRES
DB_ADDR: postgres
DB_DATABASE: keycloak
DB_USER: keycloak
DB_SCHEMA: public
DB_PASSWORD: password
KEYCLOAK_USER: admin
KEYCLOAK_PASSWORD: Pa55w0rd
# Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the PostgreSQL JDBC driver documentation in order to use it.
#JDBC_PARAMS: "ssl=true"
ports:
- 8180:8080
depends_on:
- postgres

This file defines two services: keycloak and db. Keycloak depends on db, a PostgreSQL database service configured to store Keycloak's data.

Step 2 : Launching Keycloak

After creating your docker-compose.yml file, you can start Keycloak by executing :

docker-compose up -d

This command launches the containers in the background. Keycloak will be accessible via http://localhost:8180.

Step 3 : Initial Configuration of Keycloak

Access Keycloak: Open your browser and go tohttp://localhost:8180/auth.

Keycloak authentification

Log in to the Administration Console: Use the credentials defined in the docker-compose to access Keycloak’s administration interface. In our example :

  • User : admin
  • Password : Pa55w0rd

Step 4 : Creating a New Realm

  • Create a Realm: Launch Keycloak and create a new Realm. A realm in Keycloak represents an isolated space where you can manage your users, credentials, roles, and groups.
Create new realm
  • Set new realm name (e.g. Keycloak_springboot) :
Add a realm name

Step 5 : Creating and Configuring a New Client

  • Configure a Client: Clients are entities that can request a user’s authentication. For a Spring Boot application, you will configure a client with the openid-connect protocol.
Create new Client

Under this Realm, create a client (e.g., springboot-openid-client-app) and set it up for OAuth2/OpenID authentication.

  • Go to Clients > Create: In the Keycloak administration panel.
  • Enter the basic information: Such as the Client ID and Root URL.
  • Configure the OIDC settings: Like the Valid Redirect URIs and other parameters as needed.
Configure client ID
Set default configuration
Add URL redirection to spring boot app

Step 6: Creating a Role for the Client

This process is a fundamental step in managing access rights in Keycloak as roles allow defining sets of permissions for users.

Here we see how a new role is created in Keycloak for our application. This role will be crucial for managing access and permissions within the application.

Create new role

By creating a role, the administrator prepares the system to assign basic access, which will likely be used for new users or for users who need standard permissions in the application.

We proceed to create a new “user” role in the Keycloak administration interface for the realm called “Keycloak_SpringBoot”.

Add new role name

In the “Role name” field, we can see that the administrator is entering the name of the new role, which appears to be “user”. The description field is empty, suggesting that the administrator may choose to provide additional details about the role or leave it without a description for now.

Step 6: Creating a New User

In the realm of identity and access management, Keycloak stands out as a versatile identity server that provides a rich interface for administering users and their roles within an application. The first step involves creating a new user in Keycloak.

Create new user

The image above reveals the management screen of a specific user in Keycloak, where fundamental details such as the unique ID, email address, email verification, as well as personal information like the first name and last name are displayed and can be edited.

Configure user fields

Every user can be enabled or disabled, allowing fine control over access to the application.

Additionally, required actions can be assigned, prompting the user to complete certain tasks such as confirming their email or updating their password.

This administration interface clearly illustrates how easily Keycloak allows administrators to maintain security while effectively managing user access rights.

You can see various information and configurations for a user created in a specific realm of Keycloak, identified here as “Keycloak_SpringBoot”. Here is what we can interpret from the different fields :

  • ID: A unique identifier assigned to the user within Keycloak.
  • Created at: The date and time this user was created in the system.
  • Username: The username, used to log into the application.
  • Email: The email address associated with the user, which can also be used for communications and potentially for password recovery.
  • Email verified: An indicator showing whether the user’s email address has been verified or not.
  • First name and Last name: The user’s first and last name, used for personal identification in the application.
  • Enabled: A switch indicating whether the user’s account is active and can be used to log in.
  • Required user actions: Actions that the user might be required to complete, such as updating the password or verifying the email.

Step 7 : Adding Permissions for the User

Assigning roles to this user determines their permissions within the application and is a key step in managing users in Keycloak.

On the first user management screen, we can see that a specific user, “my-user,” currently has no security identifiers (or credentials) configured.

Add Credentials

This is a crucial page where administrators can set or reset user passwords, a fundamental step to ensure that access to the application is secure. The “Set password” button allows assigning a password to the user, thus strengthening the first line of defense for user account security.

The second phase leads us directly into the process of setting a password for “my-user."

Define new password

We are presented with a simple form where a new password can be entered and confirmed, ensuring that accidental keystrokes do not cause an error in the creation of the password.

The “Temporary” option is available, which would be useful if the administrator wants the user to change this password at the next login, a common practice when initializing accounts or resetting forgotten passwords. Once the password is set and saved, the user “my-user” will be able to access applications protected by Keycloak using their new credentials.

Step 8 : Assigning the Role to the User

In Keycloak’s user management, this step involves key elements for defining and controlling roles and access.

On the “Role Mapping” tab of a user in Keycloak. Here, the roles assigned to the user are displayed, and it’s possible to assign or remove roles to refine the user’s permissions.

For example, a default role is visible but not inherited, indicating it was assigned directly rather than through a group or another parent role.

Assign role to new user

Through the “Assign roles to my-user account” dialog box, we will be able to manage the specific roles assigned to a user. In this example, the user is assigned the “user” role, a role likely intended for general access to the application.

Choose role for user

Step 9: Modifying the Default Scope

The final step shows us the “Client Scopes” available in Keycloak. Scopes are collections of roles and/or permissions that determine what a user can access with their token. For example, we see scopes like “email” and “profile,” which would include permissions related to the user’s profile information.

Scopes Screen

Finally, we move to the “Permissions” tab for a specific role, here named “user”. This indicates that permissions are enabled for this role, allowing for more detailed permissions to be set for actions that the user can perform within this role.

Permissions Screen

Each of these steps illustrates the detailed process and the flexibility that Keycloak offers for managing user rights, essential for securing and customizing the user experience within modern applications.

Conclusion

This first part of our practical guide was dedicated to the installation and configuration of Keycloak. We explored how Keycloak, as a powerful identity server, can be configured to manage authentication and authorization through OAuth2 and OpenID Connect.

The goal was to establish a solid foundation for the security of our applications.

With Keycloak ready for use, the next step will be to integrate this configuration into a Spring Boot application.

In the second part of this guide, we will put into practice what we have prepared by using Keycloak to secure a REST API, demonstrated by authentication tests with Postman.

Stay tuned to discover how to fully leverage Keycloak in the development of secure and modern applications.

Références

To deepen your knowledge and assist in your implementation, here are some recommended resources :

These resources provide comprehensive information on configuration, best practices, and guidelines for securing your applications with Keycloak and Spring Security. They will help you better understand the concepts discussed in this article and explore advanced use cases.

--

--