1

I want to write a servlet with which I can create a new session.

The servlet requires the user to authenticate with BASIC authentication and returns the standard session cookie (using HttpServletRequest#getSession(true)). However, if the client uses the received session cookie in his next request instead of BASIC authentication it is not authenticated. The server recognizes the session but it doesn't contain the user information.

I'm using Tomcat and after a bit of debugging the reason is also obvious: the user information (Principal) is added to session upon authentication. However when the first BASIC authentication is taking place no session exists yet as this will be created by the servlet. Does anyone have idea how to solve this problem?

Artem Malchenko
  • 2,320
  • 1
  • 18
  • 39
sithmein
  • 437
  • 3
  • 11

1 Answers1

2

After one night of sleep [1] I believe I have come up with a working solution myself. The following snippet (using JAX-RS, but it shouldn't be too difficult to translate it to plain servlet code) does the trick if the calling client will follow redirects:

public Response getSessionCookie() {
  boolean sessionExists = m_servletRequest.getSession(false) != null;
  if (sessionExists) {
    return Response.noContent().build();
  } else {
    HttpSession session = m_servletRequest.getSession();
    return Response.status(Status.TEMPORARY_REDIRECT)
        .header("Location",
           m_uriInfo.getAbsolutePathBuilder().matrixParam("jsessionid", session.getId()).build())
        .build();
  }
}

The first request will create a session and redirect the client to the same address but with the session ID in the URL (which is important). The client will follow the request and send the same BASIC authentication data again but now it will be registered in the existing session. The second invocation of the method above will simply return an empty response with the session cookie that can now be used for subsequent requests. Note that the session cookie is different for me in the second response but looking at Tomcat code this seems to be deliberate (successful authentication will always create a new session).

[1] Sleep is highly underestimated!

sithmein
  • 437
  • 3
  • 11