0

I am using Spring Session 1.0.1. I need to execute some logic when the user logs out, and I need to rely on the HTTP session being invalidated to cover the case where the user fails to explicitly log out.

The standard Spring Security SessionDestroyedEvent includes any applicable SecurityContext, but the Spring Session version of SessionDestroyedEvent only contains the session id. By the time this event fires, the session is no longer held by the SessionRepository so it can't be looked up by id.

Is there any way to retrieve the SecurityContext from the expired session using Spring Session?

fap
  • 663
  • 1
  • 5
  • 14
NTyler
  • 1,397
  • 1
  • 12
  • 20

2 Answers2

2

Unfortunately there is not. The problem is that at the time Redis fires the event, the session is already gone. Furthermore, the event received from Redis does not contain the original information. This means there is no way to retrieve the SecurityContext.

For updates on this please track spring-projects/spring-session/issues/4

Rob Winch
  • 21,440
  • 2
  • 59
  • 76
0

For sring-session 1.1+ with Redis https://docs.spring.io/spring-session/docs/current/reference/html5/#httpsession-httpsessionlistener

You must configure HttpSessionEventPublisher and after that spring-session will propagate sessionDestroy event

@Configuration
@EnableRedisHttpSession
public class RedisHttpSessionConfig {

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

        // ...
}

So you can use standard spting SessionDestroyedEvent listener

@Component
public class SessionDestroyListener implements ApplicationListener<SessionDestroyedEvent> {

    @Override
    public void onApplicationEvent(SessionDestroyedEvent event) {
        logger.debug("session destroyed {}", event.getId());
        if(!event.getSecurityContexts().isEmpty()) {
           ...
        }
    }
}
user1516873
  • 5,060
  • 2
  • 37
  • 56