【发布时间】:2016-05-21 09:43:05
【问题描述】:
希望你没事。
我对 Django CSRF cookie 有疑问。 我告诉你: 首先,我有一个自动将所有 CSRF cookie 标头 Ajax 放入的 JS 代码。直到一段时间它工作正常,但我注意到以下几点:
在 Firefox 和 Chrome 的隐身模式下,CSRF cookie 不起作用,发送一个空值。
在正常版本的 Chrome 中不发送任何 cookie,因此,没有 CSRF。
其次,我注意到另一个缺点:
在唯一一个 CSRF cookie 正确发送的浏览器中,正常模式下是 firefox。当我删除 cookie 并再次发出请求时,这会向我发送一个空值。
有人有办法解决这个问题吗?
然后我展示了将 cookie 设置为 CSRF 令牌的 JS 代码:
$(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));
}
});
根据额外信息告诉他们,并尝试这些其他问题中提出的解决方案,但未解决。
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)
【问题讨论】:
标签: ajax django python-3.x cookies django-csrf