How to reset JSESSIONID

It is considered good security practice to reset a session cookie when authenticating a user.

How to do this with Java?

My attempt is successful so far, but I was wondering if there is a better way:

public static HttpSession resetSessionId(HttpSession session, HttpServletRequest request) { session.invalidate(); session = request.getSession(true); return session; } 
+7
source share
4 answers

Your answer seems optimal. Another way is to directly manipulate the chefs this way:

  Cookie cookie = new Cookie ("JSESSIONID", "randomValue"); cookie.setMaxAge( 0 ); 

so you create a new cookie with the same name and expired immediately, but I do not recommend going that way, since yours is much cleaner and pretty obvious to anyone familiar with the basic Servlet APIs.

+2
source

I only transmit the request from which I am getting the session. If the session does not exist yet, there is no point in creating it for its invalidity. This also happens if the session has just been created by the container (due to the first HTTP user request directly in the login form).

 public static ... (HttpServletRequest request) { HttpSession session = request.getSession(false); if (session!=null && !session.isNew()) { session.invalidate(); } 
+3
source

Tomcat (since version 6.0.24 AFAIK) can automatically change sessionId during authentication - while you use standard servlet verification mechanisms (basic, forms-based authentication). This can be configured using changeSessionIdOnAuthentication for the basic authentication valve: http://tomcat.apache.org/tomcat-6.0-doc/config/valve.html

+2
source

Another way (and not the best way) is to call "changeSessionId (existingSession)" org.apache.catalina.session.StandardManager , which will change the session ID of the current session to a new randomly generated session ID.

To call this method, you must use the StandardManager Mbean. See Tomcat MBeans

Pseudocode:

ObjectName contextObjectName = new ObjectName ("Catalina: type = Manager, path = / whatever, host = whateverhost");

mbeanServer.invoke (contextObjectName, "changeSessionId", new Object [] {session}, new String [] {"javax.servlet.http.HttpSession"});

+1
source

All Articles