DEV Community

Pham Xuan Hoang Long
Pham Xuan Hoang Long

Posted on

The Simplest Way to Integrate Keycloak with Spring Boot 3

Keycloak is a fantastic open-source Identity and Access Management tool, but integrating it into a Spring Boot application can sometimes feel overwhelming for beginners.

In this quick guide, I'll show you the simplest way to secure your Spring Boot 3 REST APIs using Keycloak as an OAuth2 Resource Server. We will go straight to the code!


Step 1: Add the required dependencies

First, you don't need any complex Keycloak adapters anymore! Spring Security has built-in support for OAuth2 Resource Servers. Just add this to your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security-oauth2-resource-server</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure application.yaml

Next, tell Spring Boot where your Keycloak server is running. You only need to provide the issuer-uri of your Keycloak Realm:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          # Replace with your actual Keycloak URL and Realm Name
          issuer-uri: http://localhost:8180/realms/demo-keycloak
Enter fullscreen mode Exit fullscreen mode

(Spring Boot will automatically fetch the public keys from Keycloak to validate incoming JWTs!)


Step 3: Setup Security Configuration

Now, let's configure SecurityFilterChain to protect our endpoints and enable the OAuth2 Resource Server.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/public-api/**").permitAll() // Public endpoints
                .anyRequest().authenticated() // Protect everything else
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt()); // Enable JWT validation

        return http.build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Get Current User Info in Controller

How do you know who is calling your API after they are authenticated? It's extremely simple! Just use @AuthenticationPrincipal:

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/profile")
    public String getUserProfile(@AuthenticationPrincipal Jwt jwt) {
        // Get Keycloak User ID
        String keycloakId = jwt.getSubject(); 

        // You can also extract custom claims!
        String username = jwt.getClaimAsString("preferred_username");
        String email = jwt.getClaimAsString("email");

        return "Hello " + username + "! Your ID is: " + keycloakId;
    }
}
Enter fullscreen mode Exit fullscreen mode

🎯 Conclusion

That's it! With just a few lines of configuration, your Spring Boot app is now securely integrated with Keycloak using modern OAuth2 standards. No messy XML, no deprecated Keycloak adapters.

If you want to see the complete working project, including custom User and Avatar upload integrations, check out my GitHub Repository:
👉 hoanglong2534/spring-keycloak

Happy coding! 💻🔥

Top comments (0)