Search code examples
javaspring-bootsessionspring-security

Spring Security requiring login at every request


I feel like the default behaviour of persisting a successful login has changed in Spring Security.

My security config:

@Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity)
        throws Exception {
    httpSecurity
            .authorizeHttpRequests(authReg -> authReg
                    .anyRequest().authenticated()
            )
            // without this I need to login at every request
            .sessionManagement(sess -> sess
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            )
            .httpBasic(
                    Customizer.withDefaults()
            )
            .csrf(AbstractHttpConfigurer::disable); // DEV ONLY
    return httpSecurity.build();
}

Why would I need to specify the session-creation-policy now to achieve the effect of not having to log in every time, thus using an established session.

Especially since the docs tell me "This is done automatically by default, so no additional code is necessary".

Spring Boot 3.2.2, Spring Security 6.2.1


Solution

  • This section of the documentation might explain the behavior you are facing:

    Configuring Persistence for Stateless Authentication

    Some authentication mechanisms like HTTP Basic are stateless and, therefore, re-authenticates the user on every request.