Search code examples
javaspring-securitycsrf

built in method for retrieving csrf token


I have enabled csrf in Spring Security 3.2.9.RELEASE. I have found on the web these options for obtaining the csrf token:

include token is http response headers

OR

manually create a GET api to retrieve it

@RequestMapping(method = RequestMethod.GET, value = "/csrf")
    public @ResponseBody String retrieveCsrfToken(HttpServletRequest request) throws Exception {
        if (null != request.getSession(false)) {
            System.out.println("session exist ");
        }
        CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        return token.getToken();
    }

Is there no built in mechanism to retrieve it?
What is the intended default way to obtain the token?

All other csrf functionality is already coded/built in (by spring) except for this one piece of how to obtain the token. I feel like I missing something.


Solution

  • spring-security-web module allows to access the CSRF token in a view by referencing $_csrf parameter. As per 6.4.3. Include the CSRF Token docs this can be done as part of form submission:

    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    

    or stored in <meta> tag:

    <meta name="_csrf" content="${_csrf.token}"/>
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    

    for further reading through JavaScript:

    $(function () {
      var token = $("meta[name='_csrf']").attr("content");
      var header = $("meta[name='_csrf_header']").attr("content");
      $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
      });
    });