Include the CSRF Token in Spring Security | Code Factory

Reference Link : Link

Form Submissions

To implement spring security you must include the CSRF token in all PATH, POST, PUT, and DELETE methods. One way to approach this is to use the _csrf request attribute to obtain the current CsrfToken. An example of doing this with a JSP is shown below:

*Note : If you are using Spring MVC <form:form> tag or Thymeleaf 2.1+ and are using @EnableWebSecurity, the CsrfToken is automatically included for you (using the CsrfRequestDataValueProcessor).

Ajax and JSON Requests

If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:

You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:

CookieCsrfTokenRepository

There can be cases where users will want to persist the CsrfToken in a cookie. By default the CookieCsrfTokenRepository will write to a cookie named XSRF-TOKEN and read it from a header named X-XSRF-TOKEN or the HTTP parameter _csrf.

You can configure CookieCsrfTokenRepository in XML using the following:

You can configure CookieCsrfTokenRepository in Java Configuration using: