如何在 Spring Security 中启用会话和设置会话超时

新手上路,请多包涵

我是 Spring Security 的新手,我正在研究登录、注销和会话超时功能。我参考 这篇 文档配置了我的代码。我的代码如下所示:

 @Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests().antMatchers("/admin/**")
        .access("hasRole('ROLE_USER')").and().formLogin()
        .loginPage("/login").failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and().logout().logoutSuccessUrl("/login?logout").and().csrf();
    http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired");
}

覆盖类 AbstractSecurityWebApplicationInitializer

 import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

    @Override
    public boolean enableHttpSessionEventPublisher() {
        return true;
    }

}

我需要澄清我是否做对了,如果它看起来不错,那么我需要在哪里设置会话超时。我是完全基于注释来做的。

原文由 raju vaishnav 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 711
2 个回答

我能够通过仅在 web.xml 中添加以下配置来解决上述问题。任何更好的方法都会被接受。

  <session-config>
    <session-timeout>20</session-timeout>
</session-config>

原文由 raju vaishnav 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您正在使用 JavaConfig 并且不想使用 XML,您可以创建一个 HttpSessionListener 并使用 getSession().setMaxInactiveInterval() ,然后在 Initializer 中添加 onStartup()

 public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        System.out.println("session created");
        event.getSession().setMaxInactiveInterval(15);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
       System.out.println("session destroyed");
    }
}

然后在初始化器中:

 @Override
public void onStartup(ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);
    servletContext.addListener(new SessionListener());
}

原文由 munilvc 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题