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.
- package com.ekiras.ss.security.config;
- import com.ekiras.ss.security.filter.TokenAuthenticationFilter;
- import org.springframework.context.annotation.Bean;
- import org.springframework.core.Ordered;
- import org.springframework.core.annotation.Order;
- import org.springframework.security.config.annotation.web.builders.HttpSecurity;
- import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
- import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
- import org.springframework.security.config.http.SessionCreationPolicy;
- import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
- /**
- * @author ekansh
- * @since 11/4/16
- */
- @EnableWebSecurity
- @Order(Ordered.LOWEST_PRECEDENCE-100)
- public class RestSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
- }
- }
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.
No comments: