简体   繁体   English

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

[英]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 我正在使用javax.servlet.http.HttpSessionListener类来侦听Spring Boot应用程序中的会话更改

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 ? 问题是,如何从HttpSessionEvent检索用户信息?

I want to delete all the files uploaded by the user after session destroy, that's why I need at least his ID 我想在会话销毁后删除用户上传的所有文件,这就是为什么我至少需要他的ID

By default, Spring Security stores the SecurityContext in the session under the key defined by HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY . 默认情况下,春季安全存储SecurityContext中所规定的项下的会话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 您可以通过httpEvent对象获取会话,并从会话中获取当前的用户信息

se.getSession() se.getSession()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Spring MVC\\Boot Controller 方法中正确检索登录的用户信息? - How to correctly retrieve the logged user information from a Spring MVC\Boot Controller method? 从 Principal 中提取数据 Java Spring Boot - Extract data from Principal in Java Spring Boot Spring 引导 2.2.6 - 安全 | 更新用户信息后如何更新 Principal - Spring Boot 2.2.6 - Security | How to update Principal after updating user's information Spring 启动 oauth2:无 userInfo 端点 - 如何直接在客户端从 JWT 访问令牌加载身份验证(主体) - Spring boot oauth2: No userInfo endpoint - How to load the authentication (Principal) from the JWT access token directly in the client 在Spring Boot OAuth 2中无法从主体对象获取用户详细信息 - Not able to get user details from principal object in Spring boot OAuth 2 将权限和用户主体从 rest 客户端传递到服务器 spring 启动 - Passing authorities and user principal from rest client to server spring boot 如何从 spring-boot 千分尺检索指标 - How to retrieve metrics from spring-boot micrometer Spring Boot JPA 如何从多对多表中检索数据? - Spring Boot JPA how to retrieve data from a ManyToMany table? 如何在 spring 启动后请求中从 json 检索值 - how to retrieve a value from json in spring boot in post request 从 JWT 令牌获取 Spring Boot 资源服务器中的主体 - Get principal in Spring Boot resource server from JWT token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM