How can I configure spring-session to support HeaderHttpSessionStrategy and CookieHttpSessionStrategy in the same application?
I have a project that wants to support android, ios, pc web. I'm trying to use https://github.com/ spring-projects / spring-session, can it just be an in-app config to support the HttpSession token and the remainder?
if possible how can i customize it?
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.
you can use spring BeanFactoryPostProcessor to overwrite postProcessAfterInitialization () to set up SessionRepositoryFilter httpSessionStrategy by calling setHttpSessionStrategy () method after initializing it in spring.