How can I configure spring-session to support HeaderHttpSessionStrategy and CookieHttpSessionStrategy in the same application?
2 answers
One thing that worked for me was to override the code ***HttpSessionStrategy
using both Cookie and Header implementations.
You can see the concrete implementation of these classes here:
- https://github.com/spring-projects/spring-session/blob/master/spring-session/src/main/java/org/springframework/session/web/http/HeaderHttpSessionStrategy.java
- https://raw.githubusercontent.com/spring-projects/spring-session/master/spring-session/src/main/java/org/springframework/session/web/http/CookieHttpSessionStrategy.java
So it getRequestedSessionId
becomes:
public String getRequestedSessionId(HttpServletRequest request) {
// header part
String sessionId = request.getHeader(headerName);
if(sessionId != null && !sessionId.isEmpty())
return sessionId;
// cookie part
Map<String,String> sessionIds = getSessionIds(request);
String sessionAlias = getCurrentSessionAlias(request);
return sessionIds.get(sessionAlias);
}
onInvalidateSession
becomes:
public void onInvalidateSession(HttpServletRequest request, HttpServletResponse response) {
// header part
response.setHeader(headerName, "");
// cookie part
Map<String,String> sessionIds = getSessionIds(request);
String requestedAlias = getCurrentSessionAlias(request);
sessionIds.remove(requestedAlias);
Cookie sessionCookie = createSessionCookie(request, sessionIds);
response.addCookie(sessionCookie);
}
onNewSession
becomes:
public void onNewSession(Session session, HttpServletRequest request, HttpServletResponse response) {
// header part
response.setHeader(headerName, session.getId());
// cookie part
Set<String> sessionIdsWritten = getSessionIdsWritten(request);
if(sessionIdsWritten.contains(session.getId())) {
return;
}
sessionIdsWritten.add(session.getId());
Map<String,String> sessionIds = getSessionIds(request);
String sessionAlias = getCurrentSessionAlias(request);
sessionIds.put(sessionAlias, session.getId());
Cookie sessionCookie = createSessionCookie(request, sessionIds);
response.addCookie(sessionCookie);
}
I have used this in production for a browser / mobile REST API and it fits all my needs.
+2
source to share