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