Skip to main content

CSRF enabled Ajax requests using Spring Security

Many of you who have worked on Spring Security might be aware of the fact that Spring Security protects applications from Cross Site Request Forgery using _csrf tokens in the request sent to the web server. You can find a detailed understanding in the Spring documentation page. The objective of this post is to explain how to send _csrf tokens in the Ajax requests when we protect our application URL and application access using spring security.

How to get CSRF tokens
While we submit a form using an application that is protected with Spring Security, the form gets a default hidden parameter in the form body when using <form:form> element. The param contains the _csrf tokens to authenticate the requests in the server. In case we use other ways to create forms, we have to manually include a hidden parameter that contains name as ${_csrf.parameterName} and  value as ${_csrf.token}. For example,
 <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/

Ajax Requests
While we need  to send ajax requests in an application that is protected with Spring Security, you will most likely find 403 error in the response from the server. This is due to the fact that the server expects a _csrf token that is missing in the XHR. How do we send csrf tokens in the ajax request so the server is happy to regard our request legitimate and help us with the response we need? Well, there are two ways we can do.
  1. Generate csrf token header using spring security and set it in the ajax header.
  2. Generate csrf token using spring security and send them in the ajax request either via GET or POST.

Generate CSRF Tokens
Spring security provides specific taglib that we can use to generate the CSRF tokens for sending them in the XHR requests.
 <%@taglib prefix="sec" uri=""%>
The tag provides so many features that cater to security requirements. One of the usages of the taglib is to generate the metatags in the header.
 <sec:csrfMetaTags />
This will generate meta tags that are shown as below.
<meta name="_csrf_parameter" content="_csrf" />
<meta name="_csrf_header" content="X-CSRF-TOKEN" />
<meta name="_csrf" content="897dc174-8aac-44be-bf63-7395bcac87f2" />
The above well fits into if we use taglibs and JSPs. But for those who prefer to use other templates like Thymeleaf, the csrf tokens can be obtained using the approach explained in the `How to get CSRF tokens`.

CSRF token or Header?
Depending on the use case, we can set the CSRF token header or just CSRF token. For both GET or POST method, we can exploit the header approach to set the CSRF token header. But in case we need the CSRF token in the request param or request body, we can use just CSRF token. The below approach is based on setting it in the header so it fits for any requests. Assuming we have spring security metatags,
var csrfHeader = $("meta[name='_csrf_header']").attr("content");
var csrfToken  = $("meta[name='_csrf']").attr("content");
we create variables like these from meta tag content. And we set them in the header like below.
                 type : 'select',
                 source : MAKINUSCV.baseURL + '/admin/user/list/',
                 url : MAKINUSCV.baseURL + '/admin/user/list/do/',
                 ajaxOptions: {
                               beforeSend: function (xhr)
                                   xhr.setRequestHeader(csrfHeader, csrfToken);
                 success : function(response, newValue) {
                        if (response.status == 'error')
                     return response.msg;

In case we need to set in the request param or request body, we will be creating a data object in which we will set CSRF token. In that case, we will want to use the _csrf_parameter variable, not _csrf_header.
var csrfParam   = $("meta[name='_csrf_parameter']").attr("content");
var data        = {};
data[csrfParam] = csrfToken;
And pass the data object to ajax request. If its GET request, just append the csrfParam and csrfToken in the url request.


Popular posts from this blog

In-Place editing with X-Editable using Datatable plugin

In-place editing is a trending feature that can be seen in many latest web applications, a popular example would be where the editing data happens on the web page without any explicit forms or popups. Another such example I could point out is, The in-place editing is very nice in such a way that editing data seems so natural and user friendly.

To enable in-place editing, there are many free JQuery plugins available on the internet. We are discussing a very popular plugin called x-editable. Most of the time we use html tables to display data where in-place editing is enabled. Hence we need another plugin to elegantly display tables with enormous data. We use a famous JQuery plugin called datatable. Both of these plugins are used widely and free to use.

Assumption      : Bootstrap 3, JQuery used Projects

In order to enable datatable features on any ordinary table found on web page, we should initialise datatable plugin for that table. I…

Flyway Integration with Spring Boot

This post talks about how we integrated Flyway with Spring Boot and enjoyed the power of database migration seamlessly. If you have worked on Enterprise applications, data migration is really liability for your project. One wrong move, your data get lost during your production patch fixes or release updates. To mitigate such issues happening over manual migrations or even in-house programmatic data migration, we adopted Flyway, an open-source database migration tool that favors simplicity and convention over configuration. Luckily, Spring Boot naturally gels with Flyway.

Flyway               : 4.2.0
Spring Boot      : 1.5.6.RELEASE
Assumption      : Java, MySQL & Maven Used Projects

Flyway Maven Dependency
Flyway has Maven dependency that we need to specify in the pom.xml while we configure spring-boot-starter dependencies. This makes sure Spring Boot look for database migration scripts in the classpath. The default lookout path is src/main/resources/db/migration and the scripts are …