In this blog, We will see how to configure CSRF protection and how to make AngularJS allowed to send information with a CSRF token to the server.
In AngularJS, $http service reads a token from a cookie which is named by default XSRF-TOKEN and sets it in HTTP header with name X-XSRF-TOKEN. Once it is configured, now spring running on server is supposed to insert token in cookie inside HTTP header. Now server can verify that the cookie matches X-XSRF-TOKEN HTTP header.
Let's see how it can be configured with Spring.
Step 1. Configure and enable CSRF.
Spring security comes with CSRF protection enabled. Please have a look of my previous blog.
Step 2. Configure Cookie in HTTP Header to enable CSRF for AngularJS
Here is the code below in your security configuration -
Here in the second section of code, I have defined the CSRF token repository to just defined the header name which is set to the CSRF configuration.
Here the point to notice - Class CsrfHeaderFilter. Here is the code for the class.
In the code above, the class extends OncePerRequestFilter . As name suggests, Filter applied just once for very first HTTP request. It creates the cookie with token for AngularJS.
Hope this would help you.