How to configure stateless session in Spring Security
- Details
- Written by Nam Ha Minh
- Last Updated on 05 July 2024   |   Print Email
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:
- Spring Security permit all requests
- Spring security allow static resources
- How to disable CSRF in Spring Security
Learn more about Spring Security:
- Spring Security Registration and Login Tutorial
- Spring Security Role-based Authorization Tutorial
- Spring Security Remember Me Examples
- Spring Security Forgot Password Tutorial
- Spring Security Social Login with Google and Facebook
- Full Spring Security Tutorials List
Comments