0

I am trying to enable csrf protection within Spring Security and after reading this post I came up with the following config so far:

public final class CsrfTokenGeneratorFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
        response.setHeader("X-CSRF-HEADER", token.getHeaderName());
        response.setHeader("X-CSRF-PARAM", token.getParameterName());
        response.setHeader("X-CSRF-TOKEN", token.getToken());
        filterChain.doFilter(request, response);
    }
}

I also added the following to my spring-security xml file:

<custom-filter ref="csrfFilter" after="CSRF_FILTER"/>
...
<beans:bean id="csrfFilter" class="com.foo.config.CsrfTokenGeneratorFilter"/>

The problem I am facing right now is request.getAttribute("_csrf") always return a null value. Am I missing something? How am I supposed to add the _csrf value to the request?

I am using pure HTML + AJAX.

Thanks.

Community
  • 1
  • 1
dambros
  • 4,252
  • 1
  • 23
  • 39
  • In the Spring Security documentation, you will see before the form submit: – riddle_me_this Jun 26 '15 at 18:33
  • Those are for jsp , which I am not using. I am trying to get this working for Ajax/pure htmls. – dambros Jun 26 '15 at 18:34
  • According to the docs, you can submit it as part of the meta tag for Ajax: http://docs.spring.io/autorepo/docs/spring-security/3.2.0.CI-SNAPSHOT/reference/html/csrf.html. `` – riddle_me_this Jun 26 '15 at 18:35
  • The problem is exactly the same. The example given uses ${_csrf.token} which is a JSP tag. – dambros Jun 26 '15 at 18:38
  • There's a jQuery example right below it: `var token = $("meta[name='_csrf']").attr("content");` – riddle_me_this Jun 26 '15 at 18:40
  • The Jquery uses the value in the meta tag, which won't be anything due to the fact it is not a jsp. – dambros Jun 26 '15 at 18:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/81673/discussion-between-bphilipnyc-and-dambros). – riddle_me_this Jun 26 '15 at 18:47
  • the post you reference has a comment (first comment on accepted answer by OP) that links to a solution that the OP came up with. http://patrickgrimard.com/2014/01/03/spring-security-csrf-protection-in-a-backbone-single-page-app/ – ikumen Jun 26 '15 at 23:20
  • Yeah, I copied his class and followed his post to get to the point where I postes this question. Unfortuanetly I can't obtain the csrf values – dambros Jun 27 '15 at 01:30

0 Answers0