Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httpservletrequest - create new session / change session Id

I'm maintaining a Java web application.

Looking into the login code it gets an HttpSession out of HttpServletRequest via the getSession() method of HttpServletRequest. (It uses some values in the session for authentication purposes)

However I'm worried about session fixation attacks so after I have used the initial session I want to either start a new session or change the session id. Is this possible?

like image 767
AJM Avatar asked Feb 22 '10 14:02

AJM


People also ask

How do I create a new HTTP session?

To create a new session or gain access to an existing session, use the HttpServletRequest method getSession(), as shown in the following example: HttpSession mySession = request. getSession();

How do you maintain a session?

Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. There are several ways through which we can provide unique identifier in request and response.

How do you create a session variable in Java?

One servlet can create session variables and other servlets can fetch or change the value of session variables. Servlet must be a sub class of HttpServlet. Use set attribute method of Httpsession to create session variables. Use getAttribute() of Httpsession to find value of session variables.


2 Answers

The Servlet 3.0 API doesn't allow you to change the session id on an existing session. Typically, to protect against session fixation, you'll want to just create a new one and invalidate the old one as well.

You can invalidate a session like this

request.getSession(false).invalidate(); 

and then create a new session with

getSession(true) (getSession() should work too)

Obviously, if you have an data in the session that you want to persist, you'll need to copy it from the first session to the second session.

Note, for session fixation protection, it's commonly considered okay to just do this on the authentication request. But a higher level of security involves a tossing the old session and making a new session for each and every request.

like image 187
pablochan Avatar answered Oct 01 '22 04:10

pablochan


Since Java EE 7 and Servlet API 3.1 (Tomcat 8) you can use HttpServletRequest.changeSessionId() to achieve such behaviour. There is also a listener HttpSessionIdListener which will be invoked after each change.

like image 39
Jakub Kubrynski Avatar answered Oct 01 '22 02:10

Jakub Kubrynski