servletsservlet-filterssession-fixation

HttpSession invalidate is redirecting to login page


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


Solution

  • 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.