OutOfMemory in SessionRegistryImpl (Spring Security Adapter Config)

Hi,
I configured the SessionAuthenticationStrategy (Spring Security Adapter) as stated in the official documentation: Securing Applications and Services Guide
After creating a test with a lot of new sessions I encountered an OutOfMemory-Exception because the registered sessions are not cleared out of the ConcurrentHashMap used in SessionRegistryImpl. In debug mode I noticed that the SessionDestroyedEvents were not received in the SessionRegistryImpl even though the ServletListenerRegistrationBean has been defined.

After that I tried to define the SessionRegistryImpl as a separate bean, with the result that the SessionDestroyedEvents were successfully received in SessionRegistryImpl and the registered sessions were destroyed:

@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
    return new RegisterSessionAuthenticationStrategy(buildSessionRegistry());
}

@Bean
protected SessionRegistry buildSessionRegistry() {
    return new SessionRegistryImpl();
}

Is that a known behaviour? Maybe the documentation must be edited in this point.
Thanks and greetings.

1 Like

Same issue here.

Implementation code:

public class WebSecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.NEVER);

        http
                .authorizeRequests()
                .antMatchers("/api/**")
                .authenticated()
                .anyRequest()
                .permitAll();

        http.csrf().disable(); // If enabled, post request doesntt work.

        http.cors();
    }
}

I could fixed using NullAuthenticatedSessionStrategy.

In a more deeper analysis i see that SessionRegistryImpl never receive SessionDestroyedEvent.

Also tried to limit the session life time on the YAML config:

spring:
  session:
    timeout: 15s