HttpSession invalidate is redirecting to login page

1.1k views Asked by At

Hi I'm using servlet filter to change session ID on every request in order to avoid session fixation. My problem is when the method doFilter ends the application is redirected to login page. I just want to invalidate and create new session, without redirect. I don't have any other filter.

There is my doFilter code:

HttpSession session= httpServletReq.getSession();
    
if(session!=null){
  User u = session.getAttribute("user");
  session.invalidate();

  HttpSession newSession = httpServletReq.getSession(true);
  newSession.setAttribute("user", u);
}

chain.doFilter(req, resp);

The pattern on filter is ***.xhtml**

Why am I getting redirect to login?

Is it ok to change session ID on a filter?

Thanks

2

There are 2 answers

0
BalusC On BEST ANSWER

change session ID on every request in order to avoid session fixation

You should do exactly that instead of invalidating the session. You can use HttpServletRequest#changeSessionId() for this.

HttpSession session = httpRequest.getSession(false);
    
if (session != null) {
    httpRequest.changeSessionId();
}

chain.doFilter(request, response);

Do note that HttpServletRequest#getSession() defaults to auto-creating the session, so it actually never returns null. You need to explicitly pass false to HttpServletRequest#getSession(boolean).

That said, you don't necessarily need to perform this on every request, it's sufficient to perform that only at the moment when you login the user.

2
Han On

You only need method session.invalidate().

When you call 'session.invalidate()`, the existing session will be invalidated.

so the servlet request will create new session to network.