How to Seamlessly Integrate Keycloak with Spring Security in Spring Boot

This tutorial explains step‑by‑step how to add Keycloak authentication to a Spring Boot application using the Spring Security adapter, covering Maven dependencies, configuration files, custom resolvers, role mapping, session strategies, and the typical authorization code flow.

Programmer DD
Programmer DD
Programmer DD
How to Seamlessly Integrate Keycloak with Spring Security in Spring Boot

Keycloak provides adapters for popular Java applications. This article demonstrates how to integrate Keycloak with Spring Security in Spring Boot, covering dependency setup, configuration files, custom KeycloakConfigResolver, role mapping, session strategy, and the typical authorization code flow.

Adapter Integration

In a Spring application, add the keycloak-spring-security-adapter dependency:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-security-adapter</artifactId>
    <version>15.0.0</version>
</dependency>

For Spring Boot, also include the starter dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-boot-starter</artifactId>
    <version>15.0.0</version>
</dependency>

Keycloak supplies the KeycloakWebSecurityConfigurerAdapter base class. A typical security configuration looks like this:

@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

    /** Register a Keycloak AuthenticationProvider */
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(keycloakAuthenticationProvider());
    }

    /** Define the session authentication strategy */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    /** Configure HTTP security */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
            .antMatchers("/customers*").hasRole("USER")
            .antMatchers("/admin/**").hasRole("base_user")
            .anyRequest().permitAll();
    }
}
Note: The above configuration alone will not start correctly because Keycloak expects a configuration file.

When the application starts, you may encounter:

java.io.FileNotFoundException: Unable to locate Keycloak configuration file: keycloak.json

Keycloak adapters are configured via a JSON file (often exported from the Keycloak console). An example keycloak.json:

{
  "realm": "demo",
  "resource": "customer-portal",
  "realm-public-key": "MIGfMA0GCSqGSIb3D...31LwIDAQAB",
  "auth-server-url": "https://localhost:8443/auth",
  "ssl-required": "external",
  "use-resource-role-mappings": false,
  "enable-cors": true,
  "cors-max-age": 1000,
  "cors-allowed-methods": "POST, PUT, DELETE, GET",
  "cors-exposed-headers": "WWW-Authenticate, My-custom-exposed-Header",
  "bearer-only": false,
  "enable-basic-auth": false,
  "expose-token": true,
  "verify-token-audience": true,
  "credentials": { "secret": "234234-234234-234234" },
  "connection-pool-size": 20,
  "socket-timeout-millis": 5000,
  "connection-timeout-millis": 6000,
  "connection-ttl-millis": 500,
  "disable-trust-manager": false,
  "allow-any-hostname": false,
  "truststore": "path/to/truststore.jks",
  "truststore-password": "geheim",
  "client-keystore": "path/to/client-keystore.jks",
  "client-keystore-password": "geheim",
  "client-key-password": "geheim",
  "token-minimum-time-to-live": 10,
  "min-time-between-jwks-requests": 10,
  "public-key-cache-ttl": 86400,
  "redirect-rewrite-rules": { "^/wsmaster/api/(.*)$": "/api/$1" }
}

The corresponding client settings can be downloaded directly from the Keycloak console (see image below).

Injecting Client Configuration

Two approaches are shown for loading the JSON configuration.

Reuse Spring Boot Adapter Configuration

@Bean
public KeycloakConfigResolver keycloakConfigResolver() {
    return new KeycloakSpringBootConfigResolver();
}

Then add the relevant properties to application.yaml:

keycloak:
  realm: felord.cn
  auth-server-url: http://localhost:8011/auth
  resource: springboot-client
  public-client: true

Custom Resolver Implementation

@Bean
public KeycloakConfigResolver fileKeycloakConfigResolver() {
    return request -> {
        ClassPathResource classPathResource = new ClassPathResource("./keycloak.json");
        AdapterConfig adapterConfig = new ObjectMapper().readValue(classPathResource.getFile(), AdapterConfig.class);
        return KeycloakDeploymentBuilder.build(adapterConfig);
    };
}

Role Naming Strategy

Spring Security prefixes each role with ROLE_. To map Keycloak roles correctly, configure a GrantedAuthoritiesMapper such as SimpleAuthorityMapper on the KeycloakAuthenticationProvider:

KeycloakAuthenticationProvider authenticationProvider = keycloakAuthenticationProvider();
authenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());

Complete Configuration Example

Below is a minimal application.yaml for a Spring Boot client:

keycloak:
  realm: felord.cn
  auth-server-url: http://localhost:8011/auth
  resource: springboot-client
  public-client: true

The full SecurityConfig class combines the resolver bean, global authentication configuration, session strategy, and HTTP security rules as shown earlier.

Authorization Flow

When an unauthenticated user accesses a protected endpoint such as /admin/foo, they are redirected to Keycloak’s authorization endpoint:

http://localhost:8011/auth/realms/felord.cn/protocol/openid-connect/auth?response_type=code&client_id=springboot-client&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fsso%2Flogin&state=...&login=true&scope=openid

After successful login, the user is returned to the application with an authorization code, completing the standard OAuth2 authorization code flow.

Summary

Integrating Keycloak with Spring Security involves adding the appropriate adapter dependencies, providing a keycloak.json (or equivalent YAML) configuration, optionally implementing a custom KeycloakConfigResolver, mapping roles correctly, and configuring session handling. The client handles role‑to‑resource mapping while Keycloak manages users, credentials, and token issuance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootAuthenticationOAuth2Spring SecurityKeycloak
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.