当前位置: 代码迷 >> python >> Django ajax 403因为httponly cookie
  详细解决方案

Django ajax 403因为httponly cookie

热度:75   发布时间:2023-06-13 14:51:53.0

我在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在这里提到的解决方案:

我将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,但至少我可以继续使用代码