I've got a situation where I have two different webapps running on a single server, using different ports. They're both running Java's Jetty servlet container, so they both use a cookie parameter named JSESSIONID to track the session id. These two webapps are fighting over the session id.
Open a Firefox tab, and go to WebApp1
WebApp1's HTTP response has a set-cookie header with JSESSIONID=1
Firefox now has a Cookie header with JSESSIONID=1 in all it's HTTP requests to WebApp1
Open a second Firefox tab, and go to WebApp2
The HTTP reqeust to WebApp2 also has a Cookie header with JSESSIONID=1, but in the doGet, when I call req.getSession(false); I get null. And if I call req.getSession(true) I get a new Session object, but then the HTTP response from WebApp2 has a set-cookie header with JSESSIONID=20
Now, WebApp2 has a working Session, but WebApp1's session is gone. Going to WebApp1 will give me a new session, blowing away WebApp2's session.
Continue forever
So the Sessions are thrashing between each web app. I'd really like for the req.getSession(false) to return a valid session if there's already a JSESSIONID cookie defined.
One option is to basically reimplement the Session framework with a HashMap and cookies called WEBAPP1SESSIONID and WEBAPP2SESSIONID, but that sucks, and means I'll have to hack the new Session stuff into ActionServlet and a few other places.
This must be a problem others have encountered. Is Jetty's HttpServletRequest.getSession(boolean) just crappy?
I had a similar problem: One or more instances of the same application on localhost on different ports, choosen at application start time, each using its own jetty instance.
After a while, I came up with this:
Wait for jetty to initialize
use jetty's SocketManager to get the port (socketManager.getLocalPort())
set the cookie name through the SessionManager (sessionHandler.getSessionManager().setSessionCookie(String))
This way I have a difference cookie name for each instance - thus no interference anymore.
It's not Jetty's problem, it's how the cookie specification was defined. Beside the name/value pair, a cookie may also contain an expiration date, a path, a domain name, and whether the cookie is secure (i.e. intended only for SSL connections). The port number is not listed in the above ;-) so you'll need to vary either the path or the domain, as stepancheg says in his answer.
In our case we are using Tomcat, so the solution is to use different session cookie names on each instance.
In context.xml do something like
<Context sessionCookieName="JSessionId_8080">
I've been digging, and I found that in AbstractSessionManager, there's a method called getCrossContextSessionIDs(). If it returns true, then when creating a new session, Jetty will first check if JSESSIONID is set, and try to use that existing session id. I think I can set the values to true using some kind of java property on startup.
On further digging, this will only help me if I'm running two webapps in different contexts of the same Jetty (hence, cross-context). When creating a new Session object, a new JSESSIONID value is chosen. If getCrossContextSessionIDs() returns true, then it'll check if the current JSESSIONID value was created by this Jetty (including all other contexts) and if it was, it'll reuse it.
Since I'm dealing with two different Jetty instances running on two different ports, I'll need to hack Jetty's source to not do that check, or just make my own session-like framework.
It is correct behavior. You can place two your webapps to different domains, or by different paths.
You could also set the jsessionid cookie path, I believe.
Related
There is a very weird problem with our Tomcat 8.0.32 installed under Ubuntu 16.x.
This problem starts to happen accidentally and exists until tomcat server restart (so it is reproducible after it begins happen).
What happens, is that some of the requests send by timer from JS application with proper cookie: JSESSIONID= value are improperly processed: the Tomcat can not find Session object for it (from Spring MVC layer it means, that user is not authenticated). All requests with the same JSESSIONID being sent before this broken request, and all requests being send after (again with the same value of session id) - they all work fine!
We also certainly see that all headers in that request are correct (they are printed out by our application in some Filter), but Session object is not restored.
So basically it sounds like under some circumstances the Tomcat starts ignoring JSESSIONID from the requests sent via redirect from another server. And again, this does not happen always, only after some time of web-application life.
I will not provide any code here or configuration settings. First, because it looks like the poor Tomcat problem, second, because configuration is standard (out of the box after apt-install).
My question is: how can we configure the Tomcat in order to log all operations related to the JSESSIONID processing? Like that it finds session for the given ID, or does not and so on.
UPD: This never happens with more newer version of Tomcat 8.5.5. But due to some reasons it can not be updated on that particular server. My current goal is to collect evidences about this behaviour to be sure that it is a bug, or some strange default configuration that tomcat installation.
According to the docs https://tomcat.apache.org/tomcat-8.0-doc/logging.html
to enable debug logging for part of Tomcat's internals, you should configure both the appropriate logger(s) and the appropriate handler(s) to use the FINEST or ALL level. e.g.:
org.apache.catalina.session.level=ALL
java.util.logging.ConsoleHandler.level=ALL
We want to split a working application in two different .war files in order to be able to update one app without affecting the other. Each webapp will have different a UI, different users and different deploy schedule.
The easiest path seems to be sharing the same session, so if app A set session.setAttribute("foo", "bar") app B will be able to see it.
Is there a way to share the HttpSession state for both apps in the same Tomcat instance?
Our app is running on a dedicated Tomcat 5.5, there are no other apps running on the same tomcat instance, so any security concerns regarding the session sharing are not a problem. We're running multiple Tomcat instances, but the balancer is using sticky sessions.
If it's not possible or this session sharing is a really bad idea please leave a comment.
You should not share HttpSession; but you can share other objects. For example, you can register an object via JNDI and access the same object in all your apps (databases use this to pool connections).
One thing to be aware of is that two web apps will use different classloaders. If you want to share objects, they need to use the same version of the class from the same classloader (or else you will get LinkageErrors). That means either putting them in a classloader shared by both web apps (system classpath for example) OR using serialization to effectively drain and reconstitute the object in the right classloader with the correct version of the class.
If you want to use Spring, there's a project called Spring Session:
https://github.com/spring-projects/spring-session
Quoting: "HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way"
For Tomcat 8 I use the following configuration to share a session across 2 webapps:
conf/context.xml
<Context sessionCookiePath="/">
<Valve className="org.apache.catalina.valves.PersistentValve"/>
<Manager className="org.apache.catalina.session.PersistentManager">
<Store className="org.apache.catalina.session.FileStore" directory="${catalina.base}/temp/sessions"/>
</Manager>
...
</Context>
I deploy the same simple webapp twice log.war and log2.war:
/log
/log2
I can now log-in to /log and have the user displayed in /log2, this does not work with the tomcat default configuration.
The session value is set and read:
HttpSession session=request.getSession();
session.setAttribute("name",name);
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("name");
I used this project as example: https://www.javatpoint.com/servlet-http-session-login-and-logout-example
Most examples/solutions use a in-memory database which requires more setup work:
redis
hazelcast
If the two webapps are so closely coupled that they need to share objects, why are you splitting it in two? Even if you manage them somewhat independently any decent build management system should be able to create a single WAR file for deployment.
A solution like Aaron suggest with JNDI will work, but only if both webapps are running on the same server. If the units are tightly coupled and you are going to be running it on the same server anyway ... might as well have a single WAR.
If you really do want them to stand independently I'd seriously examine the data exchange between the two. Ideally you'd want them to only share relevant data with one another. This data could be passed back and forth via POST (or GET if more appropriate) parameters, you might even consider using cookies.
One way of doing this is described in this blog post: Session sharing in Apache Tomcat
Summary: Add emptySessionPath to the Connector configuration and crossContext to the Context
redison download
conf/context.xml
<Context sessionCookiePath="/">
...
<Manager className="org.redisson.tomcat.RedissonSessionManager"
configPath="${catalina.base}/conf/redisson.yaml"
readMode="REDIS" />
</Context>
conf/redisson.yaml
singleServerConfig:
address: "redis://<host>:6379"
sessionCookiePath="/" makes Tomcat use the same session id for different web apps.
RedissonSessionManager makes session to be persisted in 'shared space'
I was not able to achieve desired result with org.apache.catalina.session.FileStore PersistentManager in shared context.xml, I faced issues with session deserialization in background expiration monitor thread. It failed to deseriazile the session because it was using common classloader without webapp serializable models in classpath. Theoretically PersistentManager could be configured for each web app separately (to have proper classpath) in WEB-INF/context.xml but I failed to make it work.
org.apache.catalina.session.JDBCStore PersistentManage was promising because it expose last_access column for the session so it is not required to deserialize session_data, but it was saving app_name all the time causing same session id to be written as different rows for diffrent web apps. Thus session data was not stored in the shared place.
Spring Session has it`s own way to create session id. I was not able to find solution to force Spring Session to create same session id for different web apps.
Solution with core tomcat session id generation (with ability to generate the same for different web apps and RedissonSessionManager, which store data using session id as the only key and has it's own expiration mechanism) finally worked for me. The solution works perfectly with #SessionScope spring beans.
You can do by taking servlet context by your context root.
For retrieving variable.
request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute(variableName)
For setting variable:
request.getSession().getServletContext().getContext("/{applicationContextRoot}").setAttribute(variableName,variableValue)
Note: Both the applications should deployed in the same server.
Pls let me know if you find any problem
Tomcat 8 :
i had to do : <Context crossContext="true" sessionCookiePath="/"> in conf/context.xml
more details on config attributes here
and then to set the value(like #Qazi's answer):
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.setAttribute(variableName,variableValue)
to get the value:
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.getAttribute("user");
I developed session state server for tomcat using python.
Due to this I don't need to change the code already written for creating/accessing and destroying session. Also as there is separate server/service which is handling and storing session so not master cluster is needed. There is no session replication (as in tomcat clustering) in this case, rather this is session sharing between web farming.
You should not split your app that way in order by have high availability. You could deploy the whole app on many tomcat instances.
I am experiencing strange behavior in my Spring MVC 3.2 application, and I noticed that this only happening when the redirect is done in an alternate way; so my questions are:
Is doing 'redirect:/process' any different from
'redirect:process' for redirecting to an internal controller ?
Does the added slash make any difference, such as affecting session handling ?
What are the reasons for a lost session (or lost session attributes) ?
There's a value I read through my application; even thou I do redirects in many cases, when I add a slash before the Controller URI, on production I am sometimes losing this value.
Any clue on how to troubleshoot the lost session value ?
Note: I am using methods httpRequest.getSession().setAttribute and httpSession.getAttribute for accessing the session.
with '/' you are declaring a path from root, which is your servlet context path. without '/', usually it's going to a path relative to your current sub path. for example, if you are at '/go/url', your are pointing to '/go/url/next', not '/next'.
I didn't check spring source code but that's how it works in web browser usually.
EDIT:
I'm sorry, in Spring MVC, you must always provide full path, not just relative path. So you should do "redirect:/full/path".
Just a note: / is a slash, backslash is \.
Except for external causes because of other errors, neither redirect:process not redirect:/process should change anything as long as the session is concerned.
But those 2 redirects are not supposed to do the same thing, unless you are on the root application page. Assuming that your application runs on HTTP port 80 on server.domain, with a servlet context of myapp, and you are processing a request to http://server.domain/myapp/local/part, redirect:process would ask browser to request http://server.domain/myapp/local/part/process, when redirect:/process would ask browser to request http://server.domain/myapp/process.
What happens next depends on your controller mappings.
You probably want to analyse, what is causing the lost session attributes. One approach would be to implement your own HttpSessionAttributeListener and log in public void attributeRemoved(HttpSessionBindingEvent event) implementation. Also keep spring log level to debug.
I am using tomcat 7.0.6 with jdk 1.6.0_22
Is it possible to share session data between 2 different domains with a common subdomain such as a.mydomain.com and b.mydomain.com ?
With the default java servlet a.mydomain.com and b.mydomain.com get different sessions, but is it not possible to create a shared session for all subdomains in mydomain.com?
The problem is also that I don't directly control the commen subdomain (mydomain.com) so I can't serve any servlets from mydomain.com
Set the sessionCookieDomain attribute of <Context> element of the webapp in question to .mydomain.com (note the leading dot, this is very important). This will allow the webbrowser to share cookies among all subdomains.
If you actually have multiple webapp contexts and you want to share the session between them as well, then you also need to set sessionCookiePath attribute of <Context> element of the webapps in question to /.
In a nutshell:
<Context sessionCookieDomain=".mydomain.com" sessionCookiePath="/">
See also:
Tomcat 7 configuration reference - The Context container
For Tomcat 6 users: note that this was introduced in Tomcat 6.0.27. For those who can't upgrade, you would need a Valve to modify the cookie domain, eventually in combination with emptySessionPath attribute in <Connector> element in /conf/server.xml for the case that you've multiple webapp contexts for which you'd like to share the session.
Servlet Spec 3.0 (which is what Tomcat 7 supports) allows this by calling setDomain on SessionCookieConfig.
Details here:
http://download.oracle.com/javaee/6/api/javax/servlet/SessionCookieConfig.html
You get SessionCookieConfig progammatically at webapp init time with a ServletContextListner - or you should be able to set it the value in web.xml.
You can create your own session implementation using cookies. Sessions are handled (in most server side languages) using cookies and server side database or files. You create a token (using md5 on timestamp) and save it in file or database along with all session variables.
We want to split a working application in two different .war files in order to be able to update one app without affecting the other. Each webapp will have different a UI, different users and different deploy schedule.
The easiest path seems to be sharing the same session, so if app A set session.setAttribute("foo", "bar") app B will be able to see it.
Is there a way to share the HttpSession state for both apps in the same Tomcat instance?
Our app is running on a dedicated Tomcat 5.5, there are no other apps running on the same tomcat instance, so any security concerns regarding the session sharing are not a problem. We're running multiple Tomcat instances, but the balancer is using sticky sessions.
If it's not possible or this session sharing is a really bad idea please leave a comment.
You should not share HttpSession; but you can share other objects. For example, you can register an object via JNDI and access the same object in all your apps (databases use this to pool connections).
One thing to be aware of is that two web apps will use different classloaders. If you want to share objects, they need to use the same version of the class from the same classloader (or else you will get LinkageErrors). That means either putting them in a classloader shared by both web apps (system classpath for example) OR using serialization to effectively drain and reconstitute the object in the right classloader with the correct version of the class.
If you want to use Spring, there's a project called Spring Session:
https://github.com/spring-projects/spring-session
Quoting: "HttpSession - allows replacing the HttpSession in an application container (i.e. Tomcat) neutral way"
For Tomcat 8 I use the following configuration to share a session across 2 webapps:
conf/context.xml
<Context sessionCookiePath="/">
<Valve className="org.apache.catalina.valves.PersistentValve"/>
<Manager className="org.apache.catalina.session.PersistentManager">
<Store className="org.apache.catalina.session.FileStore" directory="${catalina.base}/temp/sessions"/>
</Manager>
...
</Context>
I deploy the same simple webapp twice log.war and log2.war:
/log
/log2
I can now log-in to /log and have the user displayed in /log2, this does not work with the tomcat default configuration.
The session value is set and read:
HttpSession session=request.getSession();
session.setAttribute("name",name);
HttpSession session=request.getSession(false);
String name=(String)session.getAttribute("name");
I used this project as example: https://www.javatpoint.com/servlet-http-session-login-and-logout-example
Most examples/solutions use a in-memory database which requires more setup work:
redis
hazelcast
If the two webapps are so closely coupled that they need to share objects, why are you splitting it in two? Even if you manage them somewhat independently any decent build management system should be able to create a single WAR file for deployment.
A solution like Aaron suggest with JNDI will work, but only if both webapps are running on the same server. If the units are tightly coupled and you are going to be running it on the same server anyway ... might as well have a single WAR.
If you really do want them to stand independently I'd seriously examine the data exchange between the two. Ideally you'd want them to only share relevant data with one another. This data could be passed back and forth via POST (or GET if more appropriate) parameters, you might even consider using cookies.
One way of doing this is described in this blog post: Session sharing in Apache Tomcat
Summary: Add emptySessionPath to the Connector configuration and crossContext to the Context
redison download
conf/context.xml
<Context sessionCookiePath="/">
...
<Manager className="org.redisson.tomcat.RedissonSessionManager"
configPath="${catalina.base}/conf/redisson.yaml"
readMode="REDIS" />
</Context>
conf/redisson.yaml
singleServerConfig:
address: "redis://<host>:6379"
sessionCookiePath="/" makes Tomcat use the same session id for different web apps.
RedissonSessionManager makes session to be persisted in 'shared space'
I was not able to achieve desired result with org.apache.catalina.session.FileStore PersistentManager in shared context.xml, I faced issues with session deserialization in background expiration monitor thread. It failed to deseriazile the session because it was using common classloader without webapp serializable models in classpath. Theoretically PersistentManager could be configured for each web app separately (to have proper classpath) in WEB-INF/context.xml but I failed to make it work.
org.apache.catalina.session.JDBCStore PersistentManage was promising because it expose last_access column for the session so it is not required to deserialize session_data, but it was saving app_name all the time causing same session id to be written as different rows for diffrent web apps. Thus session data was not stored in the shared place.
Spring Session has it`s own way to create session id. I was not able to find solution to force Spring Session to create same session id for different web apps.
Solution with core tomcat session id generation (with ability to generate the same for different web apps and RedissonSessionManager, which store data using session id as the only key and has it's own expiration mechanism) finally worked for me. The solution works perfectly with #SessionScope spring beans.
You can do by taking servlet context by your context root.
For retrieving variable.
request.getSession().getServletContext().getContext("/{applicationContextRoot}").getAttribute(variableName)
For setting variable:
request.getSession().getServletContext().getContext("/{applicationContextRoot}").setAttribute(variableName,variableValue)
Note: Both the applications should deployed in the same server.
Pls let me know if you find any problem
Tomcat 8 :
i had to do : <Context crossContext="true" sessionCookiePath="/"> in conf/context.xml
more details on config attributes here
and then to set the value(like #Qazi's answer):
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.setAttribute(variableName,variableValue)
to get the value:
ServletContext servletContext =request.getSession().getServletContext().getContext("contextPath")
servletContext.getAttribute("user");
I developed session state server for tomcat using python.
Due to this I don't need to change the code already written for creating/accessing and destroying session. Also as there is separate server/service which is handling and storing session so not master cluster is needed. There is no session replication (as in tomcat clustering) in this case, rather this is session sharing between web farming.
You should not split your app that way in order by have high availability. You could deploy the whole app on many tomcat instances.