In order to share session cookies between subdomains in your Java web application hosted with Apache Tomcat, you need to make a simple configuration change. What you simply need to do is to make a small change to your web application’s context. You might have more than one context if you have more than one web application hosted by your Tomcat web server. In my case, I have installed Tomcat on OS X, and therefore I need to change /Library/Tomcat/conf/context.xml. Note that the path to your Tomcat installation may differ depending on how you installed Tomcat and which platform you are running Tomcat on.
Nevertheless, once you have found the appropriate context, then you need to add the sessionCookieDomain attribute to the context’s root node. The value should be the domain name that you use to access your web application, prepended by a period.
<Context sessionCookieDomain=".example.com"> <!-- ... --> </Context>
If you are not accessing your web application with a domain name, then you should add the below to your /etc/hosts file (for UNIX-based environments – the path is obviously different on Windows).
127.0.0.1 example.com 127.0.0.1 subdomain1.example.com 127.0.0.1 subdomain2.example.com 127.0.0.1 subdomain3.example.com
Now, save the file and restart Tomcat.
cd /path/to/tomcat/bin ./catalina.sh stop ./catalina.sh start
Your web application’s session cookies should now be shared across subdomains. Please note that the sessionCookieDomain attribute requires a Tomcat version of at least 6.0.27.
Now, in case you have more than one context (i.e. more than one web application), and you want to share session cookies between those as well, then you also have to set the sessionCookiePath to /, like so:
<Context sessionCookieDomain=".example.com" sessionCookiePath="/"> <!-- ... --> </Context>
Thank you for reading.