如何從給定的 ID 而不是生成的 ID 在 Spring mvc 應用程式中創建會話?
我想固定會話。固定將由受信任的 ui 服務啟動。此受信任的服務轉發所有請求。因此固定不能在瀏覽器中開始。如果沒有此 ui 服務,則不打算這樣做。
提供 HttpSessionIdResolver bean 不起作用,因為它只會更改 HTTP 回應中的位置。例如,授權后 HTTP 標頭中的會話 ID。
有沒有不創建影子會話管理的解決方案?
keycloak 集成需要會話。猜猜不可能在無狀態模式下使用keycloak。
提前致謝
uj5u.com熱心網友回復:
可以使用spring-session固定會話。
@Configuration
@EnableSpringHttpSession
public class SessionConfig {
@Bean
public HttpSessionIdResolver httpSessionIdResolver() {
return new HttpSessionIdResolver() {
public List<String> resolveSessionIds(HttpServletRequest request) {
final var sessionId = request.getHeader("X-SessionId");
request.setAttribute(SessionConfig.class.getName() "SessionIdAttr", sessionId);
return List.of(sessionId);
}
public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {}
public void expireSession(HttpServletRequest request, HttpServletResponse response) {}
};
}
@Bean
public SessionRepository<MapSession> sessionRepository() {
return new MapSessionRepository(new HashMap<>()) {
@Override
public MapSession createSession() {
var sessionId =
(String)RequestContextHolder
.currentRequestAttributes()
.getAttribute(SessionConfig.class.getName() "SessionIdAttr", 0);
final var session = super.createSession();
if (sessionId != null) {
session.setId(sessionId);
}
return session;
}
};
}
您可以在#resolveSessionIds()其中讀取 ID 并存盤以備后用。
createSession()當沒有找到會話并且需要一個新會話時呼叫。在這里,您可以使用以前記住的 ID 創建會話MapSession#setId(String)。
即使有可能,IMO 也不是一個好主意。可能還有其他架構解決方案/問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422475.html
標籤:
