我正在開發 SpringBoot 有狀態應用程式。出于管理目的,我需要能夠訪問任何用戶會話并在那里修改屬性。
現在,我知道如何成功訪問當前(我的)用戶Authentication物件:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
OAuth2User principal = (OAuth2User) authentication.getPrincipal();
但是如何為任何其他用戶做同樣的事情?
是否可以通過用戶名或類似的東西找到會話?我真的很感激這個例子。
uj5u.com熱心網友回復:
沒有內置機制來執行您想要的操作,但是您可以撰寫一個自定義HttpSessionListener來保存對活動會話的參考,在到期時將其洗掉,并公開一些操作會話屬性的方法。您可能還希望將一些用戶 ID 與可用于執行用戶查找的會話相關聯,因此AuthenticationSuccessHandler還需要注冊一個來執行此操作。
您登錄的用戶管理器將如下所示:
@Service
public class LoggedInUsersManagerService implements HttpSessionListener {
// assuming you have some session storage here,
// can be something as simple as just a map
public void sessionCreated(HttpSessionEvent se) {
final HttpSession session = se.getSession();
sessionStore.put(session.getAttribute(USER_ID_ATTRIBUTE), session);
}
public void sessionDestroyed(HttpSessionEvent se) {
final HttpSession session = se.getSession();
sessionStore.remove(session.getAttribute(USER_ID_ATTRIBUTE));
}
public void doSomethingWithUserSession(UserIdType id) {
final HttpSession session = sessionStore.get(id);
if(session != null) {
//do what you need with the session attributes
}
}
}
你的 SuccessHandler 看起來像
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
HttpSession session = request.getSession();
session.setAttribute(USER_ID_ATTRIBUTE, getUserIdFromAUthentication(authentication));
//maybe do something else as well
}
}
您可以在 spring 安全配置中注冊成功處理程式,例如像這樣
http
.oauth2login()
.successHandler(myAuthenticationSuccessHandler)
請記住,在用戶仍在使用您的服務時操作會話資料并不是一個好主意,所以我不建議您這樣做,除非您絕對需要這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/512127.html
