如何在Spring Boot中从HttpSessionEvent检索主体信息?

时间:2019-07-05 13:10:07

标签: java spring spring-security spring-session

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

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

    default void sessionDestroyed(HttpSessionEvent se) {
    }
}

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

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

2 个答案:

答案 0 :(得分:2)

默认情况下,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()
}

答案 1 :(得分:0)

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

se.getSession()