Search code examples
springspring-mvccsrfspring-aop

how to view spring csrf token in filter


i am using spring mvc 4.3 version. We are using spring csrf which is default. In one of the scenario i am getting invalid token error, but I see the token whatever I have got the same is been sent to server. Is there any way I can put log message to see server response to see the csrf token that is generated. on the UI JSP page i am using tag and in the page view source I could see the token. But i want to see in a filter from server side to make sure there is no other token missing on my page.

I have two tabs on my page. Whenever I change tabs I am getting into this token invalid issue. Could you help me how to access this token details in my custom filter.

I tried the AOP like this any changes required?

@Aspect public class AfterGenerateCsrfTockenAspect {

protected transient ITSLogger logger = LogManager.getLogger(this.getClass().getName());
@AfterReturning( 
        pointcut = "org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.generateToken(..)",
        returning = "result"
    )
    public void logGeneratedCsrfToken(Object result) {
        logger.debug("CSRF token was generated.  :::: " + result);
    }

}


Solution

  • By default spring stores csrf token in session. we can access csrf token from session attributes

    String key ="org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN"
    HttpSession session = request.getSession(true);
    CsrfToken token =(CsrfToken) session.getAttribute(key);