I need to pass CSRFToken
with Ajax based post request but not sure how this can done in a best way.
Using a platform which internally checking CSRFToken
The answer above didn't work for me.
I added the following code before my ajax request:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
url: '/url/',
});
Everybody that using: var myVar = 'token', is probably the worst idea. I can print it dirrectly in the console. You need to encrypt on the client side, then decrypt on server side.
From JSP
<form method="post" id="myForm" action="someURL">
<input name="csrfToken" value="5965f0d244b7d32b334eff840...etc" type="hidden">
</form>
This is the simplest way that worked for me after struggling for 3hrs, just get the token from input hidden field like this and while doing the AJAX request to just need to pass this token in header as follows:-
From Jquery
var token = $('input[name="csrfToken"]').attr('value');
From plain Javascript
var token = document.getElementsByName("csrfToken").value;
Final AJAX Request
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
Now you don't need to disable crsf security in web config, and also this will not give you 405( Method Not Allowed) error on console.
Hope this will help people..!!