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;
}
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.
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.
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();
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With