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="http://www.springframework.org/security/tags"%>
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.
$('.editable-action').editable({
                 type : 'select',
                 source : MAKINUSCV.baseURL + '/admin/user/list/action.mk',
                 url : MAKINUSCV.baseURL + '/admin/user/list/do/action.mk',
                 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.

Comments

  1. Very good ideas and this was very useful for my professional oriented. Thanks for you provides a great post and I expect to you more information. Your written style is very impressed to me and I'm waiting for your updates...
    Spoken English Classes in Chennai
    Best Spoken English Classes in Chennai
    Html5 Training in Chennai
    IELTS Coaching in Chennai
    Pega Training in Chennai
    Japanese Classes in Chennai
    TOEFL Coaching in Chennai
    Spoken English Classes in Porur
    Spoken English Classes in Anna Nagar

    ReplyDelete

Post a Comment

Popular posts from this blog

In-Place editing with X-Editable using Datatable plugin

Introduction
In-place editing is a trending feature that can be seen in many latest web applications, a popular example would be trello.com where the editing data happens on the web page without any explicit forms or popups. Another such example I could point out is, thoughtplan.com. 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

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

Thymeleaf th:remove vs th:if Processors

Interestingly Makinus team encountered a scenario where the team has to choose between th:remove and th:if processors. The situation is like this. Makinus team worked on a project and the team lead suggested to go with #Thymeleaf template instead of decades old JSP. Hence it adopted Thymeleaf and Thymelead Layout framework to do layout-ing.

Thymeleaf Layout
Thymeleaf layout is a framework that helps doing the layout work just as tiles framework does it using JSP technology. The framework has 5 processors, important of which is layout:decorate. The processor layout:decorate works in the layout-content template model where the content template is a small piece of template that replaces content part of the layout template. This works as if parent/child templating mode where parent will define layout format while the child template replaces only the specified content portions.

Head Element Merging Strategy
Thymeleaf layout uses a special strategy to merge parent and child template <head…