Friday, February 10, 2012

HTTPS: Apache, Tomcat and Session ID

If you're using HTTPS protocol in your web projects on Java, and storing some login data linked to the session ID, you've probably faced a problem with forwarding this session ID through Apache Web Server to Tomcat in cases when you need to use same session in different HTTPS calls.
Using HttpServletRequest's sessionId might not help, because Apache will overwrite it. All you need is to copy a Cookie named "JSESSIONID" from the original request, and pass it to your HTTPS calls. This will solve the problem if this Cookie presents in original HttpServletRequest:



public String getJSessionId(Cookie[] cookies)
{
   String ret = null;
   try
   {
      if (cookies != null)
      {
         for (Cookie cookie : cookies)
         {
            if ("JSESSIONID".equals(cookie.getName()))
            {
               ret = cookie.getValue();
               break;
            }
         }
      }
   }
   catch (Exception ex)
   {
      //show alarm or ignore it
   }
   return ret;
}


If you don't have a JSESSIONID in request's Cookies, use HttpServletRequest's sessionId:


String jSessionId =  getJSessionId(request.getCookies());
if (jSessionId == null
{
   jSessionId = request.getSession.getId();
   //register login data using jSessionId
}

If you have a JSESSIONID cookie in your request, Apache Web Server will use it as a session Id.

No comments:

Post a Comment