Describe the bug
Despite configuring SessionCreationPolicy.NEVER for the SecurityFilterChain (using HttpSecurity) a session will be created once an endpoint is called, as by default the request cache is enabled.
To Reproduce This will print out "Session created" if a request is issued against the test controller. Uncommenting the line to disable the request cache will lead to the expected behaviour that no sessions are created at all.
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
// .requestCache().disable()
.securityMatcher("/test")
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.build();
}
@Bean
public HttpSessionListener httpSessionListener() {
return new HttpSessionListener() {
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session created");
}
};
}
}
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return "ok";
}
}
Expected behavior
If the session creation policy is set to NEVER, no sessions should be created at all.
Comment From: jzheaux
Thanks, @mirkoadebahr.
I believe this is a documentation issue and should be addressed by https://github.com/spring-projects/spring-security/pull/12601. I'll leave this open while that is being worked on.
sessionManagement() is really only about how the session is handled around authentication. I believe the setting you are wanting is SessionCreationPolicy.STATELESS, which reasons that if authentication is stateless, then the request shouldn't be stored for later lookup. Otherwise, you can configure a NullRequestCache yourself using:
.requestCache((cache) -> cache.requestCache(new NullRequestCache()))
Comment From: marcusdacoregio
Closed with https://github.com/spring-projects/spring-security/commit/4f3faa78f7af92d097747f10b4e3f2aa1d3dd679