我在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,萤火虫向我显示crsftoken值为null,而csrftoken cookie为httpOnly。我在CSRF_COOKIE_HTTPONLY中将settings.py设置为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/

10-09 21:15