简体   繁体   中英

How to retrieve principal information from HttpSessionEvent in Spring Boot?

I am using the javax.servlet.http.HttpSessionListener class to listen for session changes in my Spring Boot applciation

public interface HttpSessionListener extends EventListener {
    default void sessionCreated(HttpSessionEvent se) {
    }

    default void sessionDestroyed(HttpSessionEvent se) {
    }
}

The question is, how can I retrieve user information from HttpSessionEvent ?

I want to delete all the files uploaded by the user after session destroy, that's why I need at least his ID

By default, Spring Security stores the SecurityContext in the session under the key defined by HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY . So, if the user is still logged in, you could do:

@Override
void sessionDestroyed(HttpSessionEvent se) {
    HttpSession session = se.getSession();
    SecurityContext context = (SecurityContext) session.getAttribute
        (HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
    Authentication authentication = context.getAuthentication();
    // drill down from here, but could be authentication.getName()
}

you can get session by the httpEvent object and from session you can get current user info

se.getSession()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM