Spring Boot session timeout

前端 未结 7 1973
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 06:28

server.session-timeout seems to be working only for embedded tomcat.

I put a log statement to check the session max interval time. After deploying the

相关标签:
7条回答
  • 2020-12-31 07:27

    Based on justin's answer showing how to set session timeout using an AuthenticationSuccessHandler with Spring Security, I created a SessionTimeoutAuthSuccessHandler:

    public class SessionTimeoutAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
      public final Duration sessionTimeout;
    
      public SessionTimeoutAuthSuccessHandler(Duration sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
      }
    
      @Override
      public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws ServletException, IOException {
        req.getSession().setMaxInactiveInterval(Math.toIntExact(sessionTimeout.getSeconds()));
        super.onAuthenticationSuccess(req, res, auth);
      }
    }
    

    In use:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
          .anyRequest().authenticated()
          .and().formLogin().loginPage("/login")
          .successHandler(new SessionTimeoutAuthSuccessHandler(Duration.ofHours(8))).permitAll()
          .and().logout().logoutUrl("/logout").permitAll();   
      }
    ...
    }
    

    Edit Extending from SavedRequestAwareAuthenticationSuccessHandler rather than SimpleUrlAuthenticationSuccessHandler to ensure that original requests is not lost after re-authentication.

    0 讨论(0)
提交回复
热议问题