You know, REST APIs should be stateless which means no sessions should be created on the server side to store client states. The default session creation policy used by Spring Security is IF_REQUIRED, meaning that Spring Security will only create a session if required.

So to achieve statelessness for your REST APIs implemented in Spring framework, you need to set session creation policy to STATELESS in your security configuration class.

If you use Spring Security 5.x, the code to set statelessness would be like this:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			...
			.and()
			
			.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
			
	}
	
}

With Spring Security 6.x or later, the code to set statelessness is slightly different, as show below:

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    	
    	http.authorizeHttpRequests(...)
    		.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    	return http.build();    	
    }
}

Note that with session creation policy set to STATELESS, Spring Security will never create a session and will never use it to obtain the security context. But other components in your Java web application may still create sessions.

If you set the session creation policy to NEVER, Spring Security will never create a session but will use one if it already exists. This means to achieve true statelessness for your REST APIs, you should set the session creation policy to STATELESS.

In any case, you will see a cookie named JSESSIONID always created - this is the default behavior of a servlet container or Java EE application server. It has nothing to do with statelessness, so don’t worry about it.

Watch the following video to see the coding in a real project:

 

Related Spring Security Articles:

 

Learn more about Spring Security:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Add comment