我在 Django 中遇到了一个关于 CSRF 的奇怪问题。以下是相关部分:
在我的 javascript 文件中,我有:
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));
}
$(function () {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
})
$.post('/api/jpush',
$.param({'recipients': recipients, 'message': message, 'url': url,
'url_title': url_title, 'priority': priority,
'csrftoken': getCookie('csrftoken')}),
...
那么我认为:
def push(request):
return render(request, 'api/push.html')
def jpush(request):
tmplData = {'result': False}
if not request.POST:
return HttpResponseBadRequest(request)
elif request.POST.viewkeys() & {'recipients', 'message', 'priority'}:
tmplData = { 'results': send(request.POST) }
return JsonResponse(tmplData)
....
在我的模板中:
<form id="push" class="form-horizontal" action="" method="post">{% csrf_token %}
但是,当我使用 ajax 发布时,我收到 403 错误,并且 firebug 显示 crsftoken 值为 null,并且 csrftoken cookie 为 httpOnly。我已在 settings.py
中将 CSRF_COOKIE_HTTPONLY
设置为 False,所以我不明白为什么 cookie 被强制为 httpOnly。我使用的是 Django 1.10。
谢谢
最佳答案
所以我根据这里提到的kambiz找到了一个解决方案:Django CSRF check failing with an Ajax POST request
我将ajax参数部分修改为:
$.post('/api/jpush',
$.param({'recipients': recipients, 'message': message, 'url': url,
'url_title': url_title, 'priority': priority,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()}),
...
这仍然没有回答为什么 Django 强制 csfr cookie 作为 httponly,但至少我可以继续使用代码
关于javascript - Django ajax 403 因为 httponly cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42141126/