spring HttpSessionListener无法运作

l7wslrjt  于 2022-11-21  发布在  Spring
关注(0)|答案(3)|浏览(158)

我已经实现了HttpSessionListiner,但是它不工作。用调试器检查了它--进入servlet后会创建新的会话,登录后JSESSION_ID会改变,但是session.getCreateTime()保持不变(会话保持不变?)。使用注解,Spring Security。也许我错过了Spring Security中的一些配置?

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.log4j.Logger;

@WebListener
public class SessionListener implements HttpSessionListener {

    private static int totalActiveSessions;
    private static final Logger log = Logger.getLogger(SessionListener.class);  

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        totalActiveSessions++;
        log.warn("sessionCreated - add one session into counter");
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        totalActiveSessions--;
        log.debug("sessionDestroyed - deleted one session from counter");
    }
}
k97glaaz

k97glaaz1#

@Bean
public ServletListenerRegistrationBean<HttpSessionListener> sessionListener() {
    return new ServletListenerRegistrationBean<HttpSessionListener>(new sessionListener());
}

此Bean注册了我的侦听器。我尚未找到其他解决方案。

5us2dqdw

5us2dqdw2#

虽然不是发布者的特定问题,但另一个问题是会话实际上没有被创建,这意味着您的侦听器没有被正确地触发。如果您使用Spring Security,默认会话创建策略是SessionCreationPolicy.IF_REQUIRED。
您可以根据需要在Web安全Java配置中更改此设置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
    protected void configure(HttpSecurity http) throws Exception {
        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
    }
}

来源:https://www.baeldung.com/spring-security-session

2eafrhcq

2eafrhcq3#

为了避免会话固定攻击,Spring在用户通过身份验证后更改会话ID。

public class SessionListener implements HttpSessionListener, HttpSessionIdListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SessionListener.class);

    public SessionListener() {
    }

    @Override
    public void sessionCreated(final HttpSessionEvent event) {
        logIt(event.getSession(), "CREATED  ");
    }

    @Override
    public void sessionDestroyed(final HttpSessionEvent event) {
        logIt(event.getSession(), "DESTROYED");
    }

    private void logIt(HttpSession session, String action) {
        LOGGER.info("{}: {}, {}", action, session.getId(), Long.valueOf(session.getCreationTime()));
    }

    @Override
    public void sessionIdChanged(HttpSessionEvent event, String oldSessionId) {
        HttpSession session = event.getSession();
        LOGGER.info("CHANGED  : {} --> {}, {}", oldSessionId, session.getId(), Long.valueOf(session.getCreationTime()));
    }

}

相关问题