How to make spring boot never issue session cookie?

I'm developing Restful API server by using spring boot. I configured my project to use basic authentication as below.

@ComponentScan
@EnableAutoConfiguration
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
            .csrf().disable()
            .authorizeRequests().anyRequest().hasRole("USER").and()
            .httpBasic();
    }
    ...
}

But when I tested the API by Chrome-Postman-Plugin, after first call, server never require user credential. And I noticed that 'JSESSIONID' cookie was created.

There are no other security configurations in my project. I wonder why this happens...


Solution 1:

Have you tried using SessionCreationPolicy.STATELESS. There is a subtle difference between STATELESS and NEVER in the spring docs:

STATELESS: Spring Security will never create an HttpSession and it will never use it to obtain the SecurityContext.

NEVER: Spring Security will never create an HttpSession, but will use the HttpSession if it already exists.

So I would suggest that you clear all your cookies, switch it to STATELESS and try again. It could be that you had already an HttpSession when you switched to NEVER.

Solution 2:

its work for me "So I would suggest that you clear all your cookies, switch it to STATELESS and try again. It could be that you had already an HttpSession when you switched to NEVER."

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .csrf().disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated().and().httpBasic();

}

Solution 3:

I used the following options

.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.formLogin().disable()
.httpBasic().disable()
.logout().disable()

Getting the error localhost redirected you too many time

I tried after clearing the cookies. But the moment I remove the following option/line .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()... It works good. This is for oauth2login(). May be oauth2login() requires this session state. What could be the explanation?

And when I do not have this .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()... Then, it uses the cookie. I use google auth, so, once I logged in, it allows subsequent calls without the need to authenticate. All of this behavior sound reasonable and as expected.

For security reasons, I was told by an expert, to turn off cookies. I do not know what this means other than turning off the session...