Django ajax 403因为httponly cookie

时间:2017-02-09 15:51:19

标签: javascript python django csrf httponly

我在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。我在CSRF_COOKIE_HTTPONLY中将settings.py设置为False,因此我不明白为什么cookie被强制为httpOnly。我正在使用Django 1.10。

由于

1 个答案:

答案 0 :(得分:0)

所以我根据这里提到的 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,但至少我可以继续使用代码