Thursday, September 21, 2006

Are localhost:8080, [ipaddress]:8080 and [machine_name]:8080 all different for an HTTP session?

A very common (and quite frustrating) situation faced by J2EE programmers is the following:
I log in to http://localhost:8080/myApp and do stuff. Then I type http://machine_name:8080/myApp in the browser (where machine_name is the name of my machine - localhsot). The stupid app server asks me to log in again!


OR
I log in to http://localhost:8080/myApp and do stuff. My application generates a link such as "http://10.10.0.90:8080/myApp/doSomething.jsp" in the browser. In reality 10.10.0.90 is the ip address of my machine - localhsot. The stupid app server asks me to log in again!


Well, think again. May be the app server is not all that stupid after all :).


This has to do with how the browser is supposed to handle sessions.
As far as the browser is concerned, 10.10.0.90, machine_name, 127.0.0.1 and localhost are all different servers, even though in reality they might end up on the same machine. The browser has no way of knowing that they are all the same servers, and therefore it must (as per standard) try to establish a new session when the URL changes - which it does, and your webapp sends the browser to the log in page.
Diving a level deeper, the server "understands" that a particular request is bound to an existing session by looking at the JSessionID in the HTTP header of the request. For all requests subsequent to login, the browser sends this JSessionID in the HTTP header as long as the request is to the same server with which the session was
established
. For the browser, 10.10.0.90 and machine_name appear to be different servers, and hence when the server address changes, the browser doesn't end a JSessionID. Basically the browser treats these two as two separate sessions.


This may sound complex, but is actually quite simple to observe. For firefox, you get an extension called live http headers (http://livehttpheaders.mozdev.org) which displays all HTTP headers, including cookies, session ids etc. that the browser
sends. If you like (or are forced to use) IE, there's also a freeware plug-in for IE
(http://www.blunck.info/iehttpheaders.html) which does the same. Observe the headers of your requests and you'll see for yourself what I'm talking about.

This page is powered by Blogger. Isn't yours?