簡體   English   中英

如何在Spring Boot中從HttpSessionEvent檢索主體信息?

[英]How to retrieve principal information from HttpSessionEvent in Spring Boot?

我正在使用javax.servlet.http.HttpSessionListener類來偵聽Spring Boot應用程序中的會話更改

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

    default void sessionDestroyed(HttpSessionEvent se) {
    }
}

問題是,如何從HttpSessionEvent檢索用戶信息?

我想在會話銷毀后刪除用戶上傳的所有文件,這就是為什么我至少需要他的ID

默認情況下,春季安全存儲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()
}

您可以通過httpEvent對象獲取會話,並從會話中獲取當前的用戶信息

se.getSession()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM