6

What is the difference between request.getSession().getId() and request.getRequestedSessionId()? Do both of them return the same thing i.e. Session Id?

Thanks

srh
  • 1,661
  • 4
  • 30
  • 57

2 Answers2

18

request.getRequestedSessionId() will return the session id specified by the client (presumably in a cookie). request.getSession().getId() will return the server's session id (if a session does not exist, request.getSession() will create it).

The important difference is that you can't rely on the value returned by request.getRequestedSessionId(), since it may not be valid. From the documentation:

Returns the session ID specified by the client. This may not be the same as the ID of the current valid session for this request. If the client did not specify a session ID, this method returns null.

sanapala mohanarao
  • 321
  • 1
  • 2
  • 16
pablochan
  • 5,625
  • 27
  • 42
  • Would anything be achieved by checking if they match or not? – developerwjk Aug 05 '16 at 20:43
  • It's hard to say tbh. Perhaps if you gathered metrics on how these values behave normally, you could detect anomalies in that behaviour, that could potentially be attacks on your application. But this is a big what-if. – pablochan Aug 05 '16 at 20:53
  • why session ID of client may not be same as the ID of the current valid session for this request? (assuming session is still valid on client side) – srh Aug 05 '16 at 22:04
  • I imagine that in most cases the values are the same, but I would never assume it. – pablochan Aug 06 '16 at 08:35
2

HttpRequest.getRequestedSessionId() is the session id provided by the caller, usually with the JESSIONID cookie whereas HttpRequest.getGession().getId() is the id effectively used by the server.

For an ongoing session, the JESSIONID cookie, or the value of HttpRequest.getRequestedSessionId() allows the server to find the ongoing session by id.

For new sessions, you might be very tempted to set the servers session id by supplying a value via the JESSIONID cookie, i.e. the value of HttpRequest.getRequestedSessionId(). This would make it easy to correlate a chain of calls to multiple servers initiated by an initial call from the customer's browser. However, the semantics of HttpRequest.getRequestedSessionId() does not allow such chaining. Indeed, the JESSIONID cookie has an effect only for a session already existing in the server and which was previously sent to the client. If the JESSIONID cookie refers to a nonexistent session id, the server creates a new session ignoring the value of JESSIONID cookie.

You can convince yourself of the above, by reading the source code of the doGetSession(boolean) in the org.apache.catalina.connector.Request class.

Ceki
  • 26,753
  • 7
  • 62
  • 71