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.
      enabled: true
      # 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“
    protected void configure(final HttpSecurity http) throws Exception {
        // Do not create HTTP sessions for a stateless service

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
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();