Logout/Session timeout catching with spring security

后端 未结 3 1741
一向
一向 2020-11-28 21:16

I\'m using spring/spring-security 3.1 and want to take some action whenever the user logs out (or if the session is timed out). I managed to get the action done for logout b

3条回答
  •  悲哀的现实
    2020-11-28 22:04

    Ok, I got a solution working, it's not as good as I'd like, but it get's me to the result.

    I create a bean from which I can get a hold of the ApplicationContext.

    public class AppCtxProvider implements ApplicationContextAware {
    private static WeakReference APP_CTX;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        APP_CTX = new WeakReference(applicationContext);
    }
    
    public static ApplicationContext getAppCtx() {
        return APP_CTX.get();
    }
    }
    

    I implement HttpSessionEventPublisher and on destroy, i get the UserDetails via sessionRegistry.getSessionInfo(sessionId)

    Now I have the spring beans which I need to do the cleanup of the session and the user for whom the session timed out for.

    public class SessionTimeoutHandler extends HttpSessionEventPublisher {
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        super.sessionCreated(event);
    }
    
    @Override
    public void sessionDestroyed(HttpSessionEvent event) {
        SessionRegistry sessionRegistry = getSessionRegistry();
        SessionInformation sessionInfo = (sessionRegistry != null ? sessionRegistry
                .getSessionInformation(event.getSession().getId()) : null);
        UserDetails ud = null;
        if (sessionInfo != null) {
            ud = (UserDetails) sessionInfo.getPrincipal();
        }
        if (ud != null) {
                   // Do my stuff
        }
        super.sessionDestroyed(event);
    }
    
    private SessionRegistry getSessionRegistry() {
        ApplicationContext appCtx = AppCtxProvider.getAppCtx();
        return appCtx.getBean("sessionRegistry", SessionRegistry.class);
    }
    

提交回复
热议问题