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.
@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:
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.