Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset JSESSIONID

Tags:

java

jsp

servlets

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

How to do this with Java?

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

public static HttpSession resetSessionId(HttpSession session, 
      HttpServletRequest request) {
    session.invalidate();
    session = request.getSession(true);
    return session;
}
like image 317
Bozho Avatar asked Jan 29 '11 09:01

Bozho


People also ask

Why is Jsessionid in URL?

The JSESSIONID is used to ensure that loadbalancers properly route communications to and from the correct client/server partners. By default, Oracle Forms requests a JSESSIONID be generated and maintained in the URL of each exchange between the client and server.

Who sets Jsessionid cookie?

JSESSIONID is a cookie generated by Servlet containers and used for session management in J2EE web applications for HTTP protocol. If a Web server is using a cookie for session management, it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests.


3 Answers

I only pass the request from which I get the session. If a session doesn't yet exist there is no point in creating one just to invalidate it. This also holds if the session has just been created by the container (due to the user first http request directly on the login form).

public static ... (HttpServletRequest request) { 
    HttpSession session = request.getSession(false);
    if (session!=null && !session.isNew()) {
        session.invalidate();
    }
like image 144
cherouvim Avatar answered Sep 19 '22 15:09

cherouvim


Your answer seems optimal. Another way would be to directly manipulate cookes in this fashion:

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

so you create a new cookie with the same name and immediately expire it, but I don't recommend going this way since yours is much cleaner and pretty obvious to anyone who's familiar with basic Servlet APIs.

like image 25
darioo Avatar answered Sep 18 '22 15:09

darioo


Tomcat (since 6.0.24 AFAIK) can change the sessionId on authentication automatically - as long as you're using standard servlet authentication mechanisms (basic, form based authentication). This can be configured via changeSessionIdOnAuthentication for the Basic Authenticator Valve: http://tomcat.apache.org/tomcat-6.0-doc/config/valve.html

like image 33
MartinGrotzke Avatar answered Sep 18 '22 15:09

MartinGrotzke