当前位置: 代码迷 >> java >> 在Spring Session中从SessionDestroyedEvent获取安全上下文
  详细解决方案

在Spring Session中从SessionDestroyedEvent获取安全上下文

热度:121   发布时间:2023-07-27 09:46:59.0

我正在使用Spring Session 1.0.1。 当用户注销时,我需要执行一些逻辑,并且我需要依靠HTTP会话无效来解决用户无法明确注销的情况。

标准的Spring Security SessionDestroyedEvent包括任何适用的SecurityContext,但是Session Session的Spring Session版本仅包含会话ID。 在此事件触发时,会话不再由SessionRepository保留,因此无法通过ID查找该会话。

有什么办法可以使用Spring Session从过期的会话中检索SecurityContext?

不幸的是没有。 问题在于,在Redis触发事件时,会话已经消失。 此外,从Redis接收到的事件不包含原始信息。 这意味着无法检索SecurityContext。

有关此更新,请跟踪

对于Redis的sring-session 1.1+, //docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-httpsessionlistener

您必须配置HttpSessionEventPublisher,并且在该spring-session之后将传播sessionDestroy事件

@Configuration
@EnableRedisHttpSession
public class RedisHttpSessionConfig {

        @Bean
        public HttpSessionEventPublisher httpSessionEventPublisher() {
                return new HttpSessionEventPublisher();
        }

        // ...
}

因此,您可以使用标准的Sping SessionDestroyedEvent侦听器

@Component
public class SessionDestroyListener implements ApplicationListener<SessionDestroyedEvent> {

    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        logger.debug("session destroyed {}", event.getId());
        if(!event.getSecurityContexts().isEmpty()) {
           ...
        }
    }
}
  相关解决方案