Timeout handling In Spring Security

Timeout handling in Spring Security session management involves configuring the duration of user sessions. The session timeout determines how long a session remains active without any interaction from the user. Here's an example of timeout handling in Spring Security:

                
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomUserDetailsService userDetailsService;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/public/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .invalidateHttpSession(true)
                    .deleteCookies("JSESSIONID")
                    .permitAll()
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .invalidSessionUrl("/login?time=1")
                    .sessionFixation().migrateSession()
                    .sessionTimeout()
                        .maxInactiveIntervalInSeconds(1800); // Set session timeout to 30 minutes
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
        }

        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
                
            
In this example:
  • sessionManagement().sessionTimeout().maxInactiveIntervalInSeconds(1800): Configures the session timeout to 30 minutes (1800 seconds). Adjust the value as needed for your application.
  • sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED): Specifies that a session should be created only if required. This is the default behavior in Spring Security.
  • invalidSessionUrl("/login?time=1"): Redirects users to the login page with a parameter indicating an expired session if their session is invalid.

Adjust the values based on your specific requirements. This example ensures that user sessions expire after 30 minutes of inactivity, providing a balance between security and user experience.