Why your stateless Spring Boot Service still creates HTTP sessions

About two years ago I rolled out the first productive Spring Boot application within OpenShift. One of the problems we met back then was opening HTTP sessions even though we only rolled out a stateless REST server.

A few days ago, there were problems with another REST service. When I was called up and saw the following in New Relic, I was alerted:
The whole tab „Sessions“ should not appear in a stateless service.

Now you can annotate all services as stateless in Spring Boot and it will still open sessions. This is mostly due to the security module.

Two years ago it was the KeyCloak adapter, now it was Spring Security.

To fix the problem you can do the following.

Edit the application.yaml

Here we will set the session timeout to 1 minute. In case somehow sessions get still opened.
server:
   compression:
      enabled: true
   servlet.session:
      # Session timeout after 1 minute
      timeout: 120
   connection-timeout: 120

Spring Web Security

When initializing the Spring Web Security configuration, we will set the session create policy to „STATELESS“
@Override
    protected void configure(final HttpSecurity http) throws Exception {
        // Do not create HTTP sessions for a stateless service
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

Keycloak Spring Boot Adapter

While using the Keycloak Spring Boot Starter we need to extend the KeycloakWebSecurityConfigurerAdapter class and overwrite the following method:
    /**
     * Defines the session authentication strategy.
     *
     * While we are stateless, the {@link NullAuthenticatedSessionStrategy} is used
     */
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }