2

我对这里的很多部分(Django/Ajax 等)都很陌生,所以虽然我了解高级 CSFR 图片,但我对细节没有完整的处理。

由于传递的数据量较大,我需要将请求从 GET 转换为 PUT。高级别的,我正在通过 HTTPS 对 django 应用程序进行 AJAX POST API 调用。调用是从提供页面的同一域进行的。

但是,我不断收到“未设置 CSRF cookie”错误。

我正在使用 Django 1.4

为了通过 CSRF 保护,我在标题中包含了其他帖子中提到的 X-CSFRToken,并在发布的数据中包含了 {{ csrf_token }} 标记。但是,看起来该标签并没有被令牌替换。X-CSFRToken 值在请求中作为 NULL 发送。不知道为什么它没有设置。

我的印象是我不需要在页面视图中使用 ensure_csrf_cookie(),因为我在 ajaxSetup 中的 POST 之前获取了 cookie,但我也尝试过。

想法我做错了什么?

相关代码:

siteUrl = "https://localhost:8443/"

$.ajaxSetup({ 
     beforeSend: function(xhr, settings) {
         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]);
                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                     break;
                 }
             }
         }
         return cookieValue;
         }
         if (new RegExp("^"+siteUrl.replace("\\","\\\\")+".*").test(settings.url)) {
             // Only send the token to URLs from our site.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});


$.ajax({
    url: submitUrl,
    data: {'network_ids': JSON.stringify(network_ids),
            'csrfmiddlewaretoken': '{{ csrf_token }}'},
    type: 'POST',
    crossDomain: true,
    dataType: 'json',
    cotentType: 'application/json',
    success: function(mydata) {
        console.log(mydata);
    },
    error: function(jqXHR, textStatus, errorThrown) {alert(textStatus); alert(errorThrown)}
})
4

2 回答 2

1

您有多种选择:此代码清单显示您从 cookie 获取 CSRF 令牌:https ://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

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;
}
getCookie('csrftoken');

并假设 javascript 函数正在提交到 django 视图,您可以告诉该视图忽略 csrf 保护。https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')
于 2012-08-14T19:40:01.470 回答
0

Is your js served through Django's template engine? Otherwise {{ csrf_token }} won't be evaluated. Have you checked that it's actually POSTed to the server?

Also according to the docs the idea behind the ajaxSend event is that you don't have to pass the csrf_token explicitly.

I've noticed that your ajaxSetup differs slightly from the one in the docs. It might be correct, i would however copy the original from the docs.

于 2012-08-14T19:32:32.567 回答