Validating a CSRF session for POST, PUT, and DELETE

This example shows AJAX code in a JSP page that is used to validate a CSRF session for POST, PUT, and DELETE requests.

The following section provides sample codes for validating CSRF sessions for Form Submissions and REST APIs. For both validations, the CSRF cookie name in AgileApps is "XSRF-TOKEN". The validations can be performed using JavaScript or jQuery.

For Forms:

          To all the existing form fields, add a hidden field having a CSRF token value that is taken from the cookie "XSRF-TOKEN".

          Sample HTML code that you can place inside the form element is as follows:

        <input type='hidden' name='X-XSRF-TOKEN' id='X-XSRF-TOKEN' value=''></input>

Note: You can use any approach to get the cookie value.
function getCookie(cookieName) {
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(cookieName) == 0) {
            return c.substring(cookieName.length+1, c.length);
        }
    }
    return "";
}

Method 1: Using JavaScript:

Assigning value to a hidden element in the form –

var token = getCookie('XSRF-TOKEN');

document.getElementById('X-XSRF-TOKEN').value = token;

Method 2: Using jQuery

Assigning value to a hidden element in the form –

var token = $.cookie('XSRF-TOKEN'); 
$('#X-XSRF-TOKEN').val(token );

For Rest APIs:

           Intercept the ajax request and add setRequestHeader. The request header is "X-XSRF-TOKEN" and the value for the header is derived from the cookie "XSRF-TOKEN".

Method 1: Using JavaScript

var send = XMLHttpRequest.prototype.send;
var token = getCookie('XSRF-TOKEN');
XMLHttpRequest.prototype.send = function(data) {            
       this.setRequestHeader('X-XSRF-TOKEN', token );
       return send.apply(this, arguments);
};

Method 2: Using jQuery

$.ajax({
         type: 'POST',
         url: domain +  url ,
         processData: true,
         dataType: 'json',
         beforeSend: function(xhr){
             xhr.setRequestHeader('X-XSRF-TOKEN', $.cookie('XSRF-TOKEN'));
         },
         success: function(data)
         { }
});