Spring - 控制会话创建的最佳方式

时间:2014-10-29 04:36:31

标签: spring session spring-security

我目前正在从数据库中检索会话超时,因为它应该是可配置的,因此我无法在web.xml中声明它。

在我的HttpSessionEventPublisher中,我基本上从HttpSessionEvent中检索会话对象,并设置了我使用setMaxInactiveInterval从数据库中检索的会话超时值。

经过调查,每当我访问我网站中的POST网址时,都会触发HttpSessionEventPublisher并创建一个新的Session对象。我想通过仅当用户成功通过身份验证(登录,通过AuthenticationProvider)创建Session对象来控制此行为

这可能吗?

1 个答案:

答案 0 :(得分:1)

HttpSessionEventPublisher本身不会创建会话。它只是将servlet会话事件转换为spring security的等效事件。实际上,会话的创建不受Spring安全性的控制,但如果需要,它可以启动一个。

如果您只想在身份验证时设置会话超时,那么您可以扩展您使用的身份验证处理程序并在那里设置超时。

例如,以下代码扩展了SavedRequestAwareAuthenticationSuccessHandler并从应用程序属性(而不是您的情况下的数据库)中检索超时


@Component
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Value("#{appProperties['session.timeout']}")
    private int sessionTimeout;

    private final Logger logger = LoggerFactory.getLogger(AuthenticationSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication authentication) throws ServletException, IOException {

        logger.debug("onAuthenticationSuccess");

        HttpSession session = req.getSession();
        session.setMaxInactiveInterval(sessionTimeout);

        super.onAuthenticationSuccess(req, res, authentication);
    }
}