Tomcat, JSessionID, and subdomains...
http://blog.kornr.net/index.php/2009/05/29/tomcat-jsessionid-and-subdomains
Tomcat, JSessionID, and subdomains...
Imagine you're developping a web site that manages subdomains for your users, in such a way that all your users automatically get a http://user1.example.com orhttp://user2.example.com subdomain.
In order to keep the normal session available on all the subdomains, one just needs to make the session cookie associated to the smallest common domain, in this exemple, the example.com domain, so that www.example.com share the same cookie with all the other http://[whatever].example.com subdomains. Piece of cake:cookie.setDomain("example.com"), right? Almost. Just, not in a servlet container. Because, you can't.
It's amazing, but in a servlet container, you just can't tell which domain the JSESSIONID cookie is associated to. Unfortunately, Tomcat provides no container-specific way to modify this behaviour.
So, here's a simple patch that fixes the issue. It's not suited for all purpose, it just removes any www prefix that appears in the hostname, and use it as cookie domain. If there's no www prefix, the normal behaviour applies.
In apache-tomcat-6.0.18-src/java/org/apache/catalina/connector/Request.java, find the configureSessionCookie() method, and replace it with this one:
/** * Configures the given JSESSIONID cookie. * * @param cookie The JSESSIONID cookie to be configured */ protected void configureSessionCookie(Cookie cookie) { cookie.setMaxAge(-1); String contextPath = null; if (!connector.getEmptySessionPath() && (getContext() != null)) { contextPath = getContext().getEncodedPath(); } if ((contextPath != null) && (contextPath.length() > 0)) { cookie.setPath(contextPath); } else { cookie.setPath("/"); } if (isSecure()) { cookie.setSecure(true); } // CHANGES BELOW }