Integrating Keycloak with Spring Boot Applications

In today’s world, ensuring the security and proper authentication of users is a crucial aspect of any web application. Integrating a robust authentication and authorization system can be time-consuming and error-prone. This is where Keycloak, an open-source Identity and Access Management (IAM) solution, comes in handy. In this blog post, we will explore how to integrate Keycloak with Spring Boot applications to handle authentication and authorization seamlessly.

Introduction to Keycloak and Spring Boot

What is Keycloak?

Keycloak is an open-source IAM solution developed by Red Hat. It provides out-of-the-box support for various authentication protocols such as OAuth 2.0, OpenID Connect, and SAML 2.0, making it easier for developers to secure their applications. Keycloak also offers a wide range of features, including Single Sign-On (SSO), social login, user federation, and fine-grained authorization. Moreover, it provides a user-friendly administration console that simplifies managing users, roles, and permissions.

What is Spring Boot?

Spring Boot is an open-source Java-based framework developed by Pivotal Software (now part of VMware). It aims to simplify the development, deployment, and maintenance of Spring applications by providing production-ready defaults and minimizing boilerplate code. Spring Boot offers a wide array of features, such as auto-configuration, embedded web server support, and an opinionated approach to application development. This helps developers to create standalone, production-grade applications quickly and efficiently.

Setting Up Keycloak for Your Spring Boot Application

Before diving into the integration process, let’s first set up Keycloak for our Spring Boot application.

Installing and Configuring Keycloak

  1. Download the latest version of Keycloak from the official website (https://www.keycloak.org/downloads).
  2. Extract the downloaded archive and navigate to the bin directory.
  3. Start the Keycloak server by running ./kc.sh (Linux/Mac) or kc.bat (Windows).
  4. Open a web browser and access the Keycloak administration console at http://localhost:8080/auth/admin.
  5. Follow the on-screen instructions to create an initial admin user.

Creating a Realm, Client, and User

After setting up Keycloak, we need to create a realm, a client, and a user for our Spring Boot application.

  1. Log in to the Keycloak administration console using the admin user credentials.
  2. Click on the “Add realm” button and provide a name for the new realm (e.g., “SpringBootRealm”).
  3. Click on the “Clients” tab and then on the “Create” button. Provide a client ID (e.g., “spring-boot-app”) and select “openid-connect” as the client protocol.
  4. Configure the client settings as needed. For example, set the “Valid Redirect URIs” to http://localhost:8080/* to allow redirection to your Spring Boot application. Your Spring Boot app should be deployed on different host or your should change port 8080 for Keycloak or Spring Boot app.
  5. Click on the “Users” tab and then on the “Add user” button. Provide a username (e.g., “springuser”) and complete the user creation process by setting a password and any required attributes.

Now that we have Keycloak set up and configured, let’s move on to integrating it with our Spring Boot application.

Integrating Keycloak with Spring Boot Applications

Configuring Spring Boot to Use Keycloak

To integrate Keycloak with our Spring Boot application, we need to add the required dependencies and configure our application to use Keycloak for authentication and authorization.

Adding Keycloak Dependencies

Add the Keycloak Spring Boot Starter dependency to your project’s build file. For example, if you’re using Maven, add the following dependency to your pom.xml file:

<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-boot-starter</artifactId>
<version>${keycloak.version}</version>
</dependency>

If you’re using Gradle, add the following dependency to your build.gradle file:

implementation ‘org.keycloak:keycloak-spring-boot-starter:${keycloak.version}’

Configuring Keycloak in Spring Boot

Next, update your Spring Boot application’s configuration file (e.g., application.yml or application.properties) to include the necessary Keycloak configuration properties. Here’s an example configuration using application.yml:

keycloak:
auth-server-url: http://localhost:8080/auth
realm: SpringBootRealm
resource: spring-boot-app
public-client: true
principal-attribute: preferred_username
security-constraints:
– authRoles:
– user
securityCollections:
– patterns:
– “/*”

This configuration specifies the Keycloak server URL, the realm and client we created earlier, and the roles and URL patterns to secure. Be sure to update these values according to your specific Keycloak setup.

Securing Your Spring Boot Application with Keycloak

With Keycloak configured, we can now secure our Spring Boot application using Keycloak’s authentication and authorization features.

Securing REST Endpoints

To secure REST endpoints in your Spring Boot application, annotate your controller methods or classes with the @PreAuthorize annotation. This annotation allows you to specify the required roles or permissions for accessing a particular endpoint. For example:

@RestController
@RequestMapping(“/api”)
public class ApiController {

@PreAuthorize(“hasRole(‘user’)”)
@GetMapping(“/secure”)
public ResponseEntity<String> secureEndpoint() {
return ResponseEntity.ok(“Access granted to secure endpoint.”);
}

@GetMapping(“/public”)
public ResponseEntity<String> publicEndpoint() {
return ResponseEntity.ok(“Access granted to public endpoint.”);
}
}

In this example, the /api/secure endpoint requires the “user” role, while the /api/public endpoint is accessible to anyone.

Accessing User Information

Keycloak provides user information as part of the security context, which can be accessed from your Spring Boot application. To access the user’s information, inject the KeycloakPrincipal or KeycloakAuthenticationToken into your controller methods. For example:

@GetMapping(“/userinfo”)
public ResponseEntity<String> userInfo(Principal principal) {
KeycloakPrincipal<KeycloakSecurityContext> keycloakPrincipal = (KeycloakPrincipal<KeycloakSecurityContext>) principal;
AccessToken accessToken = keycloakPrincipal.getKeycloakSecurityContext().getToken();
String username = accessToken.getPreferredUsername();
String email = accessToken.getEmail();
// … other user information …
return ResponseEntity.ok(“User information: ” + username + “, ” + email);
}

In this example, we access the user’s username and email address from the Keycloak security context and return it as a response.

With these steps, your Spring Boot application is now secured using Keycloak’s powerful authentication and authorization features. You can further customize

Keycloak Single Sign-On (SSO) with Spring Boot

Understanding Single Sign-On

Single Sign-On (SSO) is an authentication process that allows users to access multiple applications with a single set of login credentials. With SSO, users only need to authenticate once, and they can then access multiple applications without needing to re-authenticate.

Keycloak SSO

Keycloak is an excellent choice for implementing SSO because it supports a wide range of protocols and integrates easily with various applications. When using Keycloak as your identity provider, you can enable SSO for your Spring Boot applications with minimal configuration.

Enabling SSO in Spring Boot Applications

With Keycloak configured as your identity provider, enabling SSO for your Spring Boot applications is a straightforward process.

Configuring Keycloak Client Settings for SSO

To enable SSO, you’ll need to configure your Keycloak client settings appropriately. Make sure that your Keycloak clients for different applications are part of the same realm, and that they share the same identity provider configuration.

Configuring Spring Boot for SSO

In your Spring Boot application, make sure that the Keycloak configuration properties in your application’s configuration file (e.g., application.yml or application.properties) are correctly set up. Ensure that the auth-server-url and realm properties are pointing to the same Keycloak server and realm used by other applications participating in the SSO process.

SSO Logout

With SSO enabled, it’s also essential to handle logout correctly to ensure that users are logged out of all applications when they choose to sign out.

Configuring Keycloak Logout URL

In your Keycloak realm settings, configure the “Front Channel Logout” option to enable logout propagation to all applications. This setting ensures that when a user logs out from one application, they are logged out of all applications using the same Keycloak session.

Implementing Logout in Spring Boot

To implement logout in your Spring Boot application, create a logout endpoint that redirects users to the Keycloak logout URL. This URL will trigger the logout process for all applications participating in the SSO process. Here’s an example of a logout endpoint:

@GetMapping(“/logout”)
public String logout(HttpServletRequest request) throws ServletException {
request.logout();
return “redirect:” + keycloakLogoutUrl;
}

In this example, keycloakLogoutUrl should be the Keycloak logout URL, which typically has the following format: http://<keycloak-server>/auth/realms/<realm>/protocol/openid-connect/logout?redirect_uri=<post-logout-redirect-url>. Make sure to replace <keycloak-server>, <realm>, and <post-logout-redirect-url> with the appropriate values for your Keycloak setup.

By following these steps, your Spring Boot applications will now support SSO and logout functionality with Keycloak, allowing users to seamlessly access multiple applications using a single set of login credentials.

Securing Spring Boot APIs with Keycloak

Keycloak and OAuth2

OAuth2 is a widely used authorization framework that allows applications to delegate access to resources without sharing their credentials. Keycloak supports OAuth2 out of the box, enabling you to secure your Spring Boot APIs using the Keycloak server as an OAuth2 authorization server.

Keycloak OAuth2 Flows

Keycloak supports various OAuth2 flows, such as the Authorization Code Flow, Implicit Flow, and Client Credentials Flow. Depending on your application’s requirements, you can choose the most suitable OAuth2 flow to secure your Spring Boot API.

Integrating Keycloak with Spring Security

Spring Security is a powerful framework that simplifies securing Spring Boot applications. By integrating Keycloak with Spring Security, you can leverage the capabilities of both solutions to secure your APIs.

Adding Keycloak Dependencies

To integrate Keycloak with Spring Security, you’ll need to add the required Keycloak dependencies to your Spring Boot project. This can be done by adding the keycloak-spring-boot-starter and keycloak-spring-security-adapter dependencies to your project’s build configuration.

Configuring Spring Security

With the Keycloak dependencies added, you’ll need to configure Spring Security to use Keycloak for authentication and authorization. This involves creating a KeycloakConfig class that extends KeycloakWebSecurityConfigurerAdapter and configuring Spring Security to use Keycloak’s authentication and authorization mechanisms.

Here’s an example of a KeycloakConfig class:

j@Configuration
@EnableWebSecurity
public class KeycloakConfig extends KeycloakWebSecurityConfigurerAdapter {// Configure Spring Security to use Keycloak’s authentication mechanism
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(keycloakAuthenticationProvider());
}

// Configure Spring Security’s HttpSecurity settings
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers(“/public/**”).permitAll()
.anyRequest().authenticated()
.and()
.logout().logoutUrl(“/logout”).permitAll();
}

// Other Keycloak configuration methods
// …
}

In this example, public API endpoints are accessible to everyone, while all other endpoints require authentication. The /logout endpoint is also configured to allow users to log out.

By integrating Keycloak with Spring Security, you can take advantage of the robust security features offered by both solutions to protect your Spring Boot APIs effectively. With this setup, your APIs will be secured using OAuth2, and your users will be able to access them using the SSO capabilities provided by Keycloak.

author avatar
Daniel Kowal
A respected Enterprise and IT Architect with over 20 years of experience specializing in the finance, banking, and insurance sectors. My expertise includes enterprise architecture, IT architecture, security, process automation, IT integration, artificial intelligence, and microservices architecture. Innovative approach and dedication to aligning IT systems with business objectives have transformed digital landscapes and optimized performance for numerous organizations.

Read more