Session Management in Tomcat - session

I have developed a simple web-app with 2 servlets A and B.
I have a few doubts related to session management for the web-app by Tomcat.
NOTE - I have disabled cookies in my web-browser (Chrome) while accessing the web-app.
1.) When the web-app is first hit, Servlet A gets invoked. Servlet A accesses the session from the request and does a simple sysout of the session hashcode. It then does a sendRedirect to servlet B.
[According to my understanding, since this is the first request, Tomcat will send a cookie containing the new session ID back to the browser. However, since we have not "encoded" the redirect URL using HttpResponse.encodeRedirectURL(), the redirect URL will not contain the session ID appended to it. Please correct me if I am wrong here.]
2.) Since cookies are disabled in my browser, it'll ignore the session ID sent back in the cookie and issue a new request to the redirect URL (which also does not have the session ID appended to it).
3.) The new request causes servlet B to be invoked, whoch also accesses the request session and does a sysout of the session hashcode.
What perplexes me is that both Servlets A and B output the same session hashcode, which means that they get the same session from both requests.
How does the second request from the browser map to the same session as before, even though no session ID has been sent ?
Thanks !

There are only 2 ways to pass sessions between requests: Cookie and URL rewrite. If you don't see the session ID in the URL, it must be cookies.
Are you sure the cookie is disabled? It should be easy to see from a HTTP header trace.

Are you certain you've disabled "in memory" cookies? Often browsers will let you disable persistent cookies which are saved to disk, but they'll still allow the transient in memory cookies which only stay resident during a browser session.
I recommend Wireshark for analyzing the HTTP stream. That way you can see the cookies that are sent and received by your browser.

This is strange.
When I tested the application yesterday, it was exhibiting a behaviour similar to what I have described. However, as I test the application now, it behaves perfectly, as I expect it to.
The cause could probably be that I did not restart my browser session after disabling cookies.
Will let you guys know if I experience the same behaviour again.
Thanks for your time guys !

Related

How HTTP redirects(302) works during an ajax call

I was asked to implement a "one session per account" limitation on an old java 7/struts 1 web application.
During development, I'm getting a behavior which I can't really understand.
So if there's an account "Account-A" currently logged in with a session "Session-1234" and then the same account gets logged in but with a different session "Session-4567" then the session "Session-1234" is marked to be invalidated in the next request performed by that session.
During the process of invalidation of the "Session-1234", one of the steps is redirecting(302) the client to the login page.
Now is what I don't understand.
If the request is coming in "synchronous" mode, everything works as expected.
User clicks some link
Server -> invalidates session and redirects(302) login.
Browser -> detects 302 looks for Location header and performs a get.
Server -> serves the resource.
Browser -> show login and update the URL.
If the request is coming in "asynchronous" mode aka AJAX, now I have problems because what happens is that the page never changes and the content of the login is displayed right there.
My question is not how to solve this "problem", but rather have a really good grasp on why it behaves like this.
If you are working with a programmatic client, you have 2 main options:
Don't use cookies, use the Authorization header and let the server emit a 401, telling the client their token is now invalid.
With your javascript client, read if the server returned a 302 response and Location header and respond to that.
#2 is basically a hack that lets you mimic the standard browsers' behavior. #1 is more appropriate for an API.

Why does JMeter HTTP Response differ from the browser response?

I have a magic link to access a website without logging in, let's say the magic link is something like this
https://key.example.exampl.tr/auth/realms/test/protocol/openid-connect/auth?client_id=my-react-client&state=ba453a80-d991-4b3b-a791-3fc2629aea03&redirect_uri=https://test.example.exampl.tr/&scope=openid&response_type=code&user_id=d0bcdd07-3198-4ab6-9cfd-d0b6341dbe00&key=7a1b4163-76e8-465c-a914-c68f16761698
when I use the link in the browser it works as expected and accesses the home page without asking me to log in. BUT when I use the same link inside HTTP GET Request using JMeter, it redirects me to the login page. Why is that happening and how to solve it?
This is happening as you browser stores specific cookies and caches for the particular request, whereas for jmeter you will request a new session every time, if you are not using HTTP Cookie Manager and HTTP Cache Manager explicitly.
Try clearing your browser history, cookies & caches and hit the same request/url, it would also redriect to the login page and behave same as jmeter does

No persistent session when connecting to API on different host

I am sending a websocket connection to the API server on a different host:
new WebSocket("ws://localhost:3000")
Whereas my front end is hosted on localhost:8080.
Inside my API's websocket connection handler I'm able to set a key on the session (with Sinatra's enable :sessions) but every time I refresh the html page, the data is lost.
Is there some requirement for sessions that the front end share the same host as the server? Or is there some way I can get around this? By the way, the front end is running on a Webpack server (Node).
I also tried adding a cross_origin allowance for the API's root route http://localhost:3000 and then doing this in the client (this example in coffeescript):
$.get "http://localhost:3000", ->
new Websocket("ws://localhost:3000")
My thinking was that maybe the session needed to be "initialized" over http:// instead of ws:// but it didn't work either. The session didn't work for the $.get "http://localhost:3000" request either. Refreshing the page shows that the session clears each time.
As we've discussed in comments, you probably have a problem with 3rd party session cookies in the browser.
Here's a scheme that you could use to work around it.
Client makes webSocket connection for the first time.
Server sends a webSocket message back with sessionID in it.
Client stores sessionID in a first party cookie (e.g. a cookie in the host web page).
User hits refresh.
Web page checks to see if it has a webSocket session cookie in the cookies for the host page. If so, it constructs a URL for the webSocket connection that includes that session ID `new Websocket("ws://localhost:3000?session=xyslkfas")
When server accepts webSocket connection, it checks the query parameters to see if there is already a session being specified. If so and that session is still valid, it hooks up that connection to that session. If not, it creates a new session and goes back to step 2.

Request and session in Servlet

I have very simple question with request and session in web. When I requested a same page page for multiple time from same browser with different tabs or through new window, session ID and session creation time was same.
This I have done from internet explorer. But when in use a different browser like google chrome and access the same page then different session id and session creation time was there. As far as my understanding says http request is stateless.
So, in my case it does not seem to be stateless within same browser as for different http request new thread is created by creating new servlet by container. So I have come to following conclusion:
If request is send from same browser with different tabs opened or through another new window at that time, the request always use the same thread for servlet operation with same session Id. If request is send from different browser then new http request is sent with new session ID.So,my question is then when it is stateless? If the request is send concurrently from different browser? If i declare scope="request"> and scope="session"> in spring then it also follows the same case ? If I am wrong in my understanding please correct me.
Spring
scope="request"
Creates new instance of bean per request.
scope="session"
Creates new instance of bean per session.And maintains instance of bean throughout the session life-cycle
Refer this for better understanding
Irrespective of browsers, Http protocol is stateless. State-fullness is implemented via cookies and session.
When request is sent from the browser, servers creates session and sends back a unique id to the client. And the client uses this id(Cookie) in subsequent request so that server could identify request and associate it with the session.
As far as requests are concerned, server creates separate thread to handle each request irrespective of window, tab or browser. However there will be only one session created per browser.
Note: Latest browsers share the session and the request made from tab, or new window will use the same session. Ex latest IE releases IE7, IE8 and IE9 are well know as Loosely-Coupled IE (LCIE). check this for more details LCIE
When your server application starts a new session, the servlet container sends a Set-Cookie header with a JSESSIONID back to the browser. The browser saves that cookie, and sends it back to the server with each request regardless of what tab you are making the request from. Obvoiusly other browsers don't have access to that cookie, so they will receive another one from the server.
When your server receives a request with a JSESSIONID cookie, it can correlate that request with requests with the same id made earlier. The serlvet container is able to associate different attributes with that id, and persist these attributes between requests. The http session object is basically a container for these attributes, to which your server application has a read/write access. Basically this is how statefullness is implemented with http sessions on top of the otherwise stateless http protocol.
As for the threads: each request can be processed by any random thread, because the session data is not bound to a particular thread. It is the servlet container that maintains the mapping from session id to the session object containing the different attributes. Consequently any random thread can access the session object belonging to the current request based on its session id.
In Spring, request scope means that a bean instance gets newly created for each request, while the lifecycle of the session scoped beans is bound to that of the http session.

Tomcat create a new session for every request

I am working on this problem for 2 days now and I am hoping that anyone here had a similar problem and a solution for that.
The problem:
It's a Spring MVC (2.5.6.) Web Application, which runs in Tomcat 6.
When the start page is requested it redirects the customer to a JSP Page (by using HTML's meta refresh tags) which loads it's content with a lot of Ajax requests (Framework: Prototype). The problem is that Tomcat creates a new session for every AJAX requests (about 67 sessions).
My first thought was that the Session Cookie is stored after the start page is loaded and the Ajax requests forces the Tomcat to create a new session. My approach was to create the session cookie by hand, but this did not make any difference.
The funny thing is that it works in some other tomcat instances, but not in the desired environment for the integration tests. In my opinion it's a Tomcat configuration issue.
After further investigation with Firebug, I found out that Tomcat creates a new Session for every request even if the right JSESSIONID is transfered to it (50B5EA0BCFE811C744CE9C1F9EDE0097):
Request Header 1:
Cookie JSESSIONID=F3206CBF2C961E125821FF22FA31A02D
Response Header 1:
Set-Cookie JSESSIONID=49E000B4D6880F4F94531AB9C78DB667; Path=/JOCA-Music-Portal JSESSIONID=50B5EA0BCFE811C744CE9C1F9EDE0097; Path=/JOCA-Music-Portal
Request Header 2:
Cookie JSESSIONID=50B5EA0BCFE811C744CE9C1F9EDE0097
Response Header 2:
Set-Cookie JSESSIONID=DCCA2D1B98D11223A6B8855800276E27; Path=/JOCA-Music-Portal
UPDATE: Further investigation isolated the problem to the Tomcat Realm configuration. We use a JDBC Realm for login. When the login is deativated, only one Session is created.
If it's activated, Tomcat creates invalidated/expired sessions, that's why a new session is created with each request. But why does Tomcat behave like this?
I'm really desperate, so any thought/hint/solution is well appreciated.
Thank you very much
You can try to analyze the HTTP traffic between your client and your server. Make sure the Cookie header is set correctly in the request and the response.
If using Firefox, you can try to debug with Firebug.
We recently ran into the same issue with an app we were developing. Come to find out, the issue is that Tomcat was modified to help prevent session fixation attacks. By default, a new session id is created on authentication. This started with 6.0.21. Check out the context configuration option 'changeSessionIdOnAuthentication' (tomcat bug/issue is https://issues.apache.org/bugzilla/show_bug.cgi?id=45255).
We ran into the same problem, but when using custom EXTERNALSSO authentication. The solution was to explicitly turn it off in the constructor of our class that inherits from org.apache.catalina.authenticator.AuthenticatorBase:
super.setChangeSessionIdOnAuthentication(false);

Resources