What is CSRF Protection?

Spring Secruity Docs:http://docs.spring.io/spring-security/site/docs/3.2.7.RELEASE/reference/htmlsingle/#csrf-include-csrf-token


When using Spring Security, all PUT, POST, and DELETE requests require “authentication” or you will get the error below


“timestamp”: 1460035702156,

“status”: 403,

“error”: “Forbidden”,

“message”: “Invalid CSRF Token ‘null’ was found on the request parameter ‘_csrf’ or header ‘X-XSRF-TOKEN’.”,

“path”: “/apply”


Since we are using AngularJS on the front-end, Angular has built in support for CSRF (which it calls “XSRF”) based on cookies.

Now SpringSecurity expects the CSRF token to be on the request as a header while AngularJS expects it to stored as a cookie named “XSRF-TOKEN”.  So on the server we need a custom filter that will send the cookie. Angular wants the cookie name to be “XSRF-TOKEN” and Spring Security provides it as a request attribute, so we just need to transfer the value from a request attribute to a cookie.  This is done in CsrfHeaderFilter.java.

NOTE: To finish the job and make it completely generic we should be careful to set the cookie path to the context path of the application (instead of hard-coded to “/”), but this is good enough for the application we are working on.

We then need to install this filter in the application, and it needs to go after the Spring Security CsrfFilter so that the request attribute is available. Since we have Spring Security protecting these resources there’s no better place than in the Spring Security filter chain, e.g. extending the SecurityConfiguration in the file SecurityConfiguration.java.  Also, in SecurityConfigration.java we have to  tell Spring Security to expect the CSRF token in the format that Angular wants to send it back (a header called “X-XRSF-TOKEN” instead of the default “X-CSRF-TOKEN”). We do this by customizing the CSRF filter in the csrfTokenRepository() method of SecurityConfiguration.java.

Leave a Reply