【问题标题】:Spring - Best way to control session creationSpring - 控制会话创建的最佳方式
【发布时间】:2014-12-24 17:10:19
【问题描述】:
我目前正在从数据库中检索会话超时,因为它应该是可配置的,所以我无法在 web.xml 中声明它。
在我的 HttpSessionEventPublisher 中,我基本上从 HttpSessionEvent 中检索会话对象,并设置使用 setMaxInactiveInterval 从数据库中检索的会话超时值。
经调查,每当我访问我网站中的 POST url 时,都会触发 HttpSessionEventPublisher 并创建一个新的 Session 对象。我想通过仅当且仅当用户成功通过身份验证(登录,通过 AuthenticationProvider)时才创建 Session 对象来控制此行为
这可能吗?
【问题讨论】:
标签:
spring
session
spring-security
【解决方案1】:
HttpSessionEventPublisher 本身不会创建会话。它只是将 servlet 会话事件转换为 spring security 的等效事件。实际上会话的创建不受 Spring Security 控制,但如果需要,它可以启动一个。
如果您只想在身份验证时设置会话超时,那么您可以扩展您使用的身份验证处理程序并在那里设置超时。
例如,以下代码扩展 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);
}
}