Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  153] [ 7]  / answers: 1 / hits: 39534  / 9 Years ago, thu, september 10, 2015, 12:00:00

I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.



I have written Code like bellow to add token when request being sent,



 var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', xyz12345);
//this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
return send.apply(this, arguments);
}


This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.



I have tried ajax function as below .
`



$.ajax({
type: POST,
url: /test/
//data: { CSRF: getCSRFTokenValue()}
}).done(function (data) {
var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
if (csrfToken) {
var cookie = JSON.parse($.cookie('helloween'));
cookie.csrf = csrfToken;
$.cookie('helloween', JSON.stringify(cookie));
}

$('#helloweenMessage').html(data.message);

});


But it is not Yet Worked.
So my question is:
How to get js side CSRF-Token Value?


More From » jquery

 Answers
61

I get my CSRF Token by this way,
By adding function :



$.get('CSRFTokenManager.do', function(data) {
var send = XMLHttpRequest.prototype.send,
token =data;
document.cookie='X-CSRF-Token='+token;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token',token);
//dojo.cookie(X-CSRF-Token, );

return send.apply(this, arguments);
};
});


Where CSRFTokenManager.do will be called from CSRFTokenManager Class.

Now It is adding token in header and cookie in every request.


[#65120] Tuesday, September 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckaylab

Total Points: 311
Total Questions: 120
Total Answers: 93

Location: Montenegro
Member since Thu, Jun 16, 2022
2 Years ago
;