Skip to main content

SpringSecurity : How to disable Session Creation for Stateless Authentication

How to disable Session Creation for Stateless Authentication


We need to disable session creation for authenticating requests based on token based authentication.
This can be easily configured by the following configurations.
  1. package com.ekiras.ss.security.config;  
  2.   
  3. import com.ekiras.ss.security.filter.TokenAuthenticationFilter;  
  4. import org.springframework.context.annotation.Bean;  
  5. import org.springframework.core.Ordered;  
  6. import org.springframework.core.annotation.Order;  
  7. import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
  8. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
  9. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
  10. import org.springframework.security.config.http.SessionCreationPolicy;  
  11. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;  
  12.   
  13. /** 
  14.  * @author ekansh 
  15.  * @since 11/4/16 
  16.  */  
  17. @EnableWebSecurity  
  18. @Order(Ordered.LOWEST_PRECEDENCE-100)  
  19. public class RestSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {  
  20.   
  21.     @Override  
  22.     protected void configure(HttpSecurity http) throws Exception {  
  23.   
  24.         http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);  
  25.   
  26.     }  
  27.   
  28.   
  29.   
  30.   
  31. }  

The above configurations, will force the application to stop creating sessions and storing authentication data in session i.e The SecurityContextHolder will not be holding the authentication for each authentication.


Pros


  • Each call will be stateless.
  • No session will be created or maintained.
  • Very good for rest applications.
  • Authentication expiry will be handled by the token expiry 

Cons


  • Response time will increase, as each request needs to be authenticated every time.
  • To maintain state of an authenticated request you need to persist token, if auth token can be used multiple times.

Comments