【问题标题】:How to retrieve principal information from HttpSessionEvent in Spring Boot?如何从 Spring Boot 中的 HttpSessionEvent 中检索主体信息?
【发布时间】:2019-07-05 13:10:07
【问题描述】:

我正在使用javax.servlet.http.HttpSessionListener 类来监听我的 Spring Boot 应用程序中的会话变化

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

    default void sessionDestroyed(HttpSessionEvent se) {
    }
}

问题是,我如何从HttpSessionEvent检索用户信息?

我想在会话销毁后删除用户上传的所有文件,这就是为什么我至少需要他的 ID

【问题讨论】:

    标签: java spring spring-security spring-session


    【解决方案1】:

    默认情况下,Spring Security 将SecurityContext 存储在HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY 定义的密钥下的会话中。所以,如果用户仍然登录,你可以这样做:

    @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()
    }
    

    【讨论】:

    【解决方案2】:

    您可以通过 httpEvent 对象获取会话,并从会话中获取当前用户信息

    se.getSession()

    【讨论】:

    • se.getSession() 返回一个StandardHttpSessionFacade 对象,该对象又包含一个session 类型为StandardSession 的字段,但问题是该字段是私有的,我不能得到它
    猜你喜欢
    • 2017-10-11
    • 2017-06-08
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多