views:

847

answers:

3

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?

+2  A: 

You can invalidate a session like this

request.getSession(false).invalidate();

and then create a new session with getSession(true) (getSession() should work to)

pablochan
Isn't that supposed to give a NullPointerException when getSession hasn't been called before?
FRotthowe
True, but I think we're assuming that the session exists.
pablochan
I would upvote you if you have used `getSession()` instead of `getSession(boolean)`.
BalusC
@BalusC: lol, I'll remember it next time ;]
pablochan
My question was assuming the session already existed at this point. Thanks for the good answer.
AJM
A: 

did this work out for you? When I do the following (to prevent session fixation):

HashMap<String, Object> attributes = new HashMap<String, Object>();
// copy/save all attributes
Enumeration<String> enames = httpSession.getAttributeNames();
while ( enames.hasMoreElements() )
{
  String name = enames.nextElement();
  if ( !name.equals( "JSESSIONID" ) )
  { 
    attributes.put( name, httpSession      
     .getAttribute( name ) );
  }      
}
// invalidate the session
httpSession.invalidate();
// create a new session
httpSession = request.getSession( true );
// "restore" the session values
for ( Map.Entry<String, Object> et : attributes.entrySet() )
{
  httpSession.setAttribute( et.getKey(), et.getValue() ); // <- java.lang.IllegalStateException: setAttribute: Session already invalidated
}

I get "java.lang.IllegalStateException: setAttribute: Session already invalidated" What am I missing?

Clemens
found the problem on my own. Had another variable pointing to the "old" session ;-) So the code above works for me too
Clemens
A: 

I have tried after invalidate the session then create the new session, but it is giving the same session id in websphere server environment. could you please help me.

Suresh pvs