Reputation: 131
hope you are fine.
I have a problem with Django CSRF cookie. I tell you: First, I have a JS code that automatically puts all the CSRF cookie headers Ajax. Until a while it worked fine, but I noticed the following:
In incognito mode both Firefox and Chrome, the CSRF cookie does not work, send a null value.
In the normal version of Chrome does not send any cookie, and therefore, no CSRF.
Second, I noticed another drawback:
In the only browser that CSRF cookie sent correctly, which was firefox in normal mode. When I remove the cookies and make a request again, this sends me a null value.
Does anyone have any idea to solve this?
Then I show my JS code that sets the cookies as CSRF token:
$(function(){
//Obtenemos la información de csfrtoken que se almacena por cookies en el cliente
var csrftoken = getCookie('csrftoken');
//Agregamos en la configuración de la funcion $.ajax de Jquery lo siguiente:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
!(/^(\/\/|http:|https:).*/.test(url));
}
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;
}
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
});
As extra information tell them that and try the solution proposed in these other questions, but not resolved.
no csrf token after ajax page load
Django - AJAX not working due to csrf token not working on windows
Django csrf in ajax POST (csrf cookie not set until {{csrf}} used)
Upvotes: 1
Views: 1501
Reputation: 131
I'm really a big stupid. The solution is easy, using exactly the JS code that I put up on my question, simply add the template tag:
{% csrf_token %}
It seems to be obvious, but is supposed to code using the cookie as CSRF. However, when this does not exist, because they have to take on the other hand, in this case the CSRF label.
Upvotes: 3