Search code examples
servletsspring-session

Session atributes missing from spring session when setting inside HttpSessionListener


In servlet based application I want to make session replication using Spring Session Data Redis. Everything works fine but for csrf security we are using owasp scrfgaurd, where in that flow session token will set at HttpSessionListener.The token is missing while validating.

I tried creating standalone code reproduce the issue.I have created SampleHttpListener and setting some attributes to the session, but these values I am not able to see at servlet level.

Please tell me anything I am missing or any other approach for this senario.

I have added source code here https://github.com/surya0420/SpringSession


Solution

  • public class CsrfGuardHttpSessionListener implements HttpSessionListener {
        @Override
        public void sessionCreated(HttpSessionEvent event) {
            HttpSession session = event.getSession();
            CsrfGuard csrfGuard = CsrfGuard.getInstance();
            csrfGuard.updateToken(session);
            if(session.getServletContext()!=null){
                session.getServletContext().setAttribute(OWASP_CSRFTOKEN,session.getAttribute(OWASP_CSRFTOKEN));
            }
    
    
        }
    

    Since session attributes are missing which are setting at HttpSessionListener level, so I am setting it to

     session.getServletContext().setAttribute(OWASP_CSRFTOKEN,session.getAttribute(OWASP_CSRFTOKEN));
    

    after session got created I am setting back the attributes at filter level as shown below at Filter level

    if(((HttpServletRequest) request).getSession().getAttribute(OWASP_CSRFTOKEN) == null) {
                    ((HttpServletRequest) request).getSession().setAttribute(OWASP_CSRFTOKEN, request.getServletContext().getAttribute(OWASP_CSRFTOKEN));
            }