Concurrent Session Control

Concurrent session control and timeout handling are two distinct aspects of session management in Spring Security. Below, I'll provide a combined example that addresses both concurrent session control and timeout handling.

Concurrent Session Control and Timeout Handling in Spring Security Example:

                
    @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()
                    .maximumSessions(1)
                        .expiredUrl("/login?expired=true")
                        .maxSessionsPreventsLogin(true) // Prevent new logins when the maximum sessions limit is reached
                    .and()
                    .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:
  • Concurrent Session Control:
    • maximumSessions(1): Limits the number of concurrent sessions per user to 1.
    • expiredUrl("/login?expired=true"): Redirects users to the login page with an expired session parameter if their session is expired.
    • maxSessionsPreventsLogin(true): Prevents new logins when the maximum sessions limit is reached.
  • Timeout Handling:
    • sessionTimeout().maxInactiveIntervalInSeconds(1800): Sets the session timeout to 30 minutes (1800 seconds).

Adjust the values and configurations based on your specific requirements and security policies. This example ensures that users are restricted to one concurrent session, and the session expires after 30 minutes of inactivity.