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.