Django CSRF检查失败,并带有Ajax POST请求

问题:Django CSRF检查失败,并带有Ajax POST请求

我可以通过我的AJAX帖子向遵循Django CSRF保护机制的人员提供帮助。我按照这里的指示进行:

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

我已经完全复制了该页面上的AJAX示例代码:

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

getCookie('csrftoken')xhr.setRequestHeader呼叫之前打印了警报内容,并确实在其中填充了一些数据。我不确定如何验证令牌是否正确,但是我鼓励它正在查找并发送一些消息。

但是Django仍然拒绝我的AJAX帖子。

这是我的JavaScript:

$.post("/memorize/", data, function (result) {
    if (result != "failure") {
        get_random_card();
    }
    else {
        alert("Failed to save card data.");
    }
});

这是我在Django中看到的错误:

[23 / Feb / 2011 22:08:29]“ POST / memorize / HTTP / 1.1” 403 2332

我确定我缺少某些东西,也许很简单,但是我不知道它是什么。我在SO周围搜索,并看到了一些有关通过csrf_exempt装饰器关闭CSRF检查以获取我的视图的信息,但是我发现这没有吸引力。我已经尝试过了,并且可以工作,但是我宁愿让POST按照Django期望的方式工作。

以防万一,这是我的观点正在做的要点:

def myview(request):

    profile = request.user.profile

    if request.method == 'POST':
        """
        Process the post...
        """
        return HttpResponseRedirect('/memorize/')
    else: # request.method == 'GET'

        ajax = request.GET.has_key('ajax')

        """
        Some irrelevent code...
        """

        if ajax:
            response = HttpResponse()
            profile.get_stack_json(response)
            return response
        else:
            """
            Get data to send along with the content of the page.
            """

        return render_to_response('memorize/memorize.html',
                """ My data """
                context_instance=RequestContext(request))

感谢您的回复!

I could use some help complying with Django’s CSRF protection mechanism via my AJAX post. I’ve followed the directions here:

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/

I’ve copied the AJAX sample code they have on that page exactly:

http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

I put an alert printing the contents of getCookie('csrftoken') before the xhr.setRequestHeader call and it is indeed populated with some data. I’m not sure how to verify that the token is correct, but I’m encouraged that it’s finding and sending something.

But Django is still rejecting my AJAX post.

Here’s my JavaScript:

$.post("/memorize/", data, function (result) {
    if (result != "failure") {
        get_random_card();
    }
    else {
        alert("Failed to save card data.");
    }
});

Here’s the error I’m seeing from Django:

[23/Feb/2011 22:08:29] “POST /memorize/ HTTP/1.1” 403 2332

I’m sure I’m missing something, and maybe it’s simple, but I don’t know what it is. I’ve searched around SO and saw some information about turning off the CSRF check for my view via the csrf_exempt decorator, but I find that unappealing. I’ve tried that out and it works, but I’d rather get my POST to work the way Django was designed to expect it, if possible.

Just in case it’s helpful, here’s the gist of what my view is doing:

def myview(request):

    profile = request.user.profile

    if request.method == 'POST':
        """
        Process the post...
        """
        return HttpResponseRedirect('/memorize/')
    else: # request.method == 'GET'

        ajax = request.GET.has_key('ajax')

        """
        Some irrelevent code...
        """

        if ajax:
            response = HttpResponse()
            profile.get_stack_json(response)
            return response
        else:
            """
            Get data to send along with the content of the page.
            """

        return render_to_response('memorize/memorize.html',
                """ My data """
                context_instance=RequestContext(request))

Thanks for your replies!


回答 0

真正的解决方案

好的,我设法找出问题所在。它位于Javascript(正如我在下面建议的)代码中。

您需要的是:

$.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]);
                     // 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;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});

而不是官方文档中发布的代码:https//docs.djangoproject.com/en/2.2/ref/csrf/

工作代码来自以下Django条目:http : //www.djangoproject.com/weblog/2011/feb/08/security/

因此,一般的解决方案是:“使用ajaxSetup处理程序而不是ajaxSend处理程序”。我不知道为什么会这样。但这对我有用:)

以前的帖子(无答案)

我实际上遇到了同样的问题。

它在更新到Django 1.2.5之后发生-在Django 1.2.4中AJAX POST请求没有错误(AJAX不受任何保护,但效果很好)。

就像OP一样,我尝试了Django文档中发布的JavaScript代码段。我正在使用jQuery 1.5。我也在使用“ django.middleware.csrf.CsrfViewMiddleware”中间件。

我尝试遵循中间件代码,但我知道它在此方面失败:

request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

然后

if request_csrf_token != csrf_token:
    return self._reject(request, REASON_BAD_TOKEN)

此“如果”为true,因为“ request_csrf_token”为空。

基本上,这意味着未设置标头。那么此JS行有什么问题吗:

xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));

我希望提供的详细信息将有助于我们解决问题:)

Real solution

Ok, I managed to trace the problem down. It lies in the Javascript (as I suggested below) code.

What you need is this:

$.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]);
                     // 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;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
});

instead of the code posted in the official docs: https://docs.djangoproject.com/en/2.2/ref/csrf/

The working code, comes from this Django entry: http://www.djangoproject.com/weblog/2011/feb/08/security/

So the general solution is: “use ajaxSetup handler instead of ajaxSend handler”. I don’t know why it works. But it works for me :)

Previous post (without answer)

I’m experiencing the same problem actually.

It occurs after updating to Django 1.2.5 – there were no errors with AJAX POST requests in Django 1.2.4 (AJAX wasn’t protected in any way, but it worked just fine).

Just like OP, I have tried the JavaScript snippet posted in Django documentation. I’m using jQuery 1.5. I’m also using the “django.middleware.csrf.CsrfViewMiddleware” middleware.

I tried to follow the the middleware code and I know that it fails on this:

request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')

and then

if request_csrf_token != csrf_token:
    return self._reject(request, REASON_BAD_TOKEN)

this “if” is true, because “request_csrf_token” is empty.

Basically it means that the header is NOT set. So is there anything wrong with this JS line:

xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));

?

I hope that provided details will help us in resolving the issue :)


回答 1

如果使用该$.ajax函数,则可以简单地将csrf令牌添加到数据主体中:

$.ajax({
    data: {
        somedata: 'somedata',
        moredata: 'moredata',
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },

If you use the $.ajax function, you can simply add the csrf token in the data body:

$.ajax({
    data: {
        somedata: 'somedata',
        moredata: 'moredata',
        csrfmiddlewaretoken: '{{ csrf_token }}'
    },

回答 2

将此行添加到您的jQuery代码中:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

并做了。

Add this line to your jQuery code:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

and done.


回答 3

问题是因为django希望将cookie中的值作为表单数据的一部分传递回去。上一个答案中的代码使javascript能够找出cookie值并将其放入表单数据中。从技术的角度来看,这是一种不错的方法,但是它确实有些冗长。

过去,我更简单地通过获取JavaScript将令牌值放入发布数据中来完成此操作。

如果您在模板中使用{%csrf_token%},则会发出带有该值的隐藏表单字段。但是,如果您使用{{csrf_token}},则只会获得令牌的裸值,因此可以在javascript中使用此代码…。

csrf_token = "{{ csrf_token }}";

然后,您可以在哈希中添加所需的键名称,然后将其作为数据提交给ajax调用。

The issue is because django is expecting the value from the cookie to be passed back as part of the form data. The code from the previous answer is getting javascript to hunt out the cookie value and put it into the form data. Thats a lovely way of doing it from a technical point of view, but it does look a bit verbose.

In the past, I have done it more simply by getting the javascript to put the token value into the post data.

If you use {% csrf_token %} in your template, you will get a hidden form field emitted that carries the value. But, if you use {{ csrf_token }} you will just get the bare value of the token, so you can use this in javascript like this….

csrf_token = "{{ csrf_token }}";

Then you can include that, with the required key name in the hash you then submit as the data to the ajax call.


回答 4

{% csrf_token %}在HTML模板放里面<form></form>

转换为:

<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />

所以为什么不像这样在您的JS中grep它:

token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()

然后通过它,例如进行一些POST,例如:

$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
    console.log(data);
});

The {% csrf_token %} put in html templates inside <form></form>

translates to something like:

<input type='hidden' name='csrfmiddlewaretoken' value='Sdgrw2HfynbFgPcZ5sjaoAI5zsMZ4wZR' />

so why not just grep it in your JS like this:

token = $("#change_password-form").find('input[name=csrfmiddlewaretoken]').val()

and then pass it e.g doing some POST, like:

$.post( "/panel/change_password/", {foo: bar, csrfmiddlewaretoken: token}, function(data){
    console.log(data);
});

回答 5

非jQuery答案:

var csrfcookie = function() {
    var cookieValue = null,
        name = 'csrftoken';
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
};

用法:

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('X-CSRFToken', csrfcookie());
request.onload = callback;
request.send(data);

Non-jquery answer:

var csrfcookie = function() {
    var cookieValue = null,
        name = 'csrftoken';
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
};

usage:

var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('X-CSRFToken', csrfcookie());
request.onload = callback;
request.send(data);

回答 6

如果您的表单在没有JS的Django中正确发布,那么您应该能够使用Ajax逐步增强它,而不会造成任何黑客攻击或csrf令牌的混乱传递。只需序列化整个表单,它将自动选择所有表单字段,包括隐藏的csrf字段:

$('#myForm').submit(function(){
    var action = $(this).attr('action');
    var that = $(this);
    $.ajax({
        url: action,
        type: 'POST',
        data: that.serialize()
        ,success: function(data){
            console.log('Success!');
        }
    });
    return false;
});

我已经使用Django 1.3+和jQuery 1.5+进行了测试。显然,这将适用于任何HTML表单,而不仅仅是Django应用。

If your form posts correctly in Django without JS, you should be able to progressively enhance it with ajax without any hacking or messy passing of the csrf token. Just serialize the whole form and that will automatically pick up all your form fields including the hidden csrf field:

$('#myForm').submit(function(){
    var action = $(this).attr('action');
    var that = $(this);
    $.ajax({
        url: action,
        type: 'POST',
        data: that.serialize()
        ,success: function(data){
            console.log('Success!');
        }
    });
    return false;
});

I’ve tested this with Django 1.3+ and jQuery 1.5+. Obviously this will work for any HTML form, not just Django apps.


回答 7

将Firefox与Firebug结合使用。触发ajax请求时,打开“控制台”选项卡。这样一来,DEBUG=True您将得到漂亮的django错误页面作为响应,甚至可以在控制台选项卡中看到ajax响应的呈现的html。

然后,您将知道错误是什么。

Use Firefox with Firebug. Open the ‘Console’ tab while firing the ajax request. With DEBUG=True you get the nice django error page as response and you can even see the rendered html of the ajax response in the console tab.

Then you will know what the error is.


回答 8

可接受的答案很可能是鲱鱼。Django 1.2.4和1.2.5之间的区别是AJAX请求需要CSRF令牌。

我在Django 1.3上遇到了这个问题,这是由于未设置CSRF cookie引起的首先。除非必须,否则Django不会设置cookie。因此,运行在Django 1.2.4上的排他或大量ajax站点可能永远不会向客户端发送令牌,然后需要令牌的升级会导致403错误。

理想的解决方法是在这里:http : //docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form
但您必须等待1.4,除非这只是跟上代码的文档

编辑

还要注意,以后的Django文档注意到jQuery 1.5中的一个错误,因此请确保您将Django建议的代码与1.5.1或更高版本一起使用:http : //docs.djangoproject.com/en/1.3/ref/contrib/csrf/#阿贾克斯

The accepted answer is most likely a red herring. The difference between Django 1.2.4 and 1.2.5 was the requirement for a CSRF token for AJAX requests.

I came across this problem on Django 1.3 and it was caused by the CSRF cookie not being set in the first place. Django will not set the cookie unless it has to. So an exclusively or heavily ajax site running on Django 1.2.4 would potentially never have sent a token to the client and then the upgrade requiring the token would cause the 403 errors.

The ideal fix is here: http://docs.djangoproject.com/en/dev/ref/contrib/csrf/#page-uses-ajax-without-any-html-form
but you’d have to wait for 1.4 unless this is just documentation catching up with the code

Edit

Note also that the later Django docs note a bug in jQuery 1.5 so ensure you are using 1.5.1 or later with the Django suggested code: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax


回答 9

似乎没有人提到过使用X-CSRFTokenheader和来在纯JS中执行此操作的方法{{ csrf_token }},因此这是一个简单的解决方案,您无需搜索cookie或DOM:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

It seems nobody has mentioned how to do this in pure JS using the X-CSRFToken header and {{ csrf_token }}, so here’s a simple solution where you don’t need to search through the cookies or the DOM:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

回答 10

由于当前答案中没有任何地方说明,因此如果您不将 js 嵌入模板中,最快的解决方案是:

<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>你的模板里面引用之前的script.js文件,然后添加csrfmiddlewaretoken到您的data字典在你的js文件:

$.ajax({
            type: 'POST',
            url: somepathname + "do_it/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

As it is not stated anywhere in the current answers, the fastest solution if you are not embedding js into your template is:

Put <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> before your reference to script.js file in your template, then add csrfmiddlewaretoken into your data dictionary in your js file:

$.ajax({
            type: 'POST',
            url: somepathname + "do_it/",
            data: {csrfmiddlewaretoken: window.CSRF_TOKEN},
            success: function() {
                console.log("Success!");
            }
        })

回答 11

我刚刚遇到了一些不同但相似的情况。不能100%确定是否可以解决您的问题,但是我通过设置POST参数’csrfmiddlewaretoken’并使用适当的cookie值字符串解决了Django 1.3的问题,该参数通常由Django的home HTML形式返回。带有'{%csrf_token%}’标签的模板系统。我没有尝试使用较旧的Django,只是在Django1.3上发生并解决了。我的问题是,通过Ajax从表单提交的第一个请求已成功完成,但从完全相同的第二次请求失败,导致了403状态,即使标头’X-CSRFToken’也已正确放置CSRF令牌值就像第一次尝试一样。希望这可以帮助。

问候,

I’ve just encountered a bit different but similar situation. Not 100% sure if it’d be a resolution to your case, but I resolved the issue for Django 1.3 by setting a POST parameter ‘csrfmiddlewaretoken’ with the proper cookie value string which is usually returned within the form of your home HTML by Django’s template system with ‘{% csrf_token %}’ tag. I did not try on the older Django, just happened and resolved on Django1.3. My problem was that the first request submitted via Ajax from a form was successfully done but the second attempt from the exact same from failed, resulted in 403 state even though the header ‘X-CSRFToken’ is correctly placed with the CSRF token value as well as in the case of the first attempt. Hope this helps.

Regards,

Hiro


回答 12

您可以将此js粘贴到您的html文件中,请记住将其放在其他js函数之前

<script>
  // using jQuery
  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;
  }

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $(document).ready(function() {
    var csrftoken = getCookie('csrftoken');
    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });
  });
</script>

You can paste this js into your html file, remember put it before other js function

<script>
  // using jQuery
  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;
  }

  function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $(document).ready(function() {
    var csrftoken = getCookie('csrftoken');
    $.ajaxSetup({
      beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
      }
    });
  });
</script>

回答 13

每个会话(即每次登录)都分配一个CSRF令牌。因此,在希望获取用户输入的某些数据并将其作为ajax调用发送给受csrf_protect装饰器保护的某个函数之前,请先尝试查找正在被调用的函数,然后再从用户获取此数据。例如,必须渲染一些模板,以便用户在其上输入数据。该模板由某些功能渲染。在此函数中,您可以按以下方式获取csrf令牌:csrf = request.COOKIES [‘csrftoken’]现在在上下文字典中传递此csrf值,针对该字典呈现相关模板。现在在该模板中编写以下行:现在,在您的javascript函数中,在发出ajax请求之前,请编写:var csrf = $(’#csrf’)。val()这将选择传递给模板的令牌的值并将其存储在变量csrf中。现在,在进行ajax调用时,在您的帖子数据中,还要传递此值:“ csrfmiddlewaretoken”:csrf

即使您未实现Django表单,这也将起作用。

实际上,这里的逻辑是:您需要可以从请求中获取的令牌。因此,您只需要确定登录后立即调用的函数即可。一旦有了此令牌,就可以再次调用ajax来获取它,或者将其传递给可被ajax访问的模板。

One CSRF token is assigned to every session ( i.e. every time you log in). So before you wish to get some data entered by user and send that as ajax call to some function which is protected by csrf_protect decorator, try to find the functions that are being called before you are getting this data from user. E.g. some template must be being rendered on which your user is entering data. That template is being rendered by some function. In this function you can get csrf token as follows: csrf = request.COOKIES[‘csrftoken’] Now pass this csrf value in context dictionary against which template in question is being rendered. Now in that template write this line: Now in your javascript function, before making ajax request, write this: var csrf = $(‘#csrf’).val() this will pick value of token passed to template and store it in variable csrf. Now while making ajax call, in your post data, pass this value as well : “csrfmiddlewaretoken”: csrf

This will work even if you are not implementing django forms.

In fact, logic over here is : You need token which you can get from request. So you just need to figure out the function being called immediately after log in. Once you have this token, either make another ajax call to get it or pass it to some template which is accessible by your ajax.


回答 14

对于遇到此问题并尝试调试的人:

1)django csrf检查(假设您要发送一个)是 这里

2)在我的情况下,将settings.CSRF_HEADER_NAME其设置为“ HTTP_X_CSRFTOKEN”,而我的AJAX调用正在发送名为“ HTTP_X_CSRF_TOKEN”的标头,因此无法正常工作。我可以在AJAX调用或Django设置中更改它。

3)如果您选择在服务器端进行更改,请找到django的安装位置,并csrf middleware在使用的.f中放置一个断点virtualenv,它将类似于:~/.envs/my-project/lib/python2.7/site-packages/django/middleware/csrf.py

import ipdb; ipdb.set_trace() # breakpoint!!
if request_csrf_token == "":
    # Fall back to X-CSRFToken, to make things easier for AJAX,
    # and possible for PUT/DELETE.
    request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')

然后,确保csrf令牌是从request.META正确获取的。

4)如果您需要更改标题等,请在设置文件中更改该变量

for someone who comes across this and is trying to debug:

1) the django csrf check (assuming you’re sending one) is here

2) In my case, settings.CSRF_HEADER_NAME was set to ‘HTTP_X_CSRFTOKEN’ and my AJAX call was sending a header named ‘HTTP_X_CSRF_TOKEN’ so stuff wasn’t working. I could either change it in the AJAX call, or django setting.

3) If you opt to change it server-side, find your install location of django and throw a breakpoint in the csrf middleware.f you’re using virtualenv, it’ll be something like: ~/.envs/my-project/lib/python2.7/site-packages/django/middleware/csrf.py

import ipdb; ipdb.set_trace() # breakpoint!!
if request_csrf_token == "":
    # Fall back to X-CSRFToken, to make things easier for AJAX,
    # and possible for PUT/DELETE.
    request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')

Then, make sure the csrf token is correctly sourced from request.META

4) If you need to change your header, etc – change that variable in your settings file


回答 15

如果有人正在努力使用axios进行这项工作,那么这对我有帮助:

import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

资料来源:https : //cbuelter.wordpress.com/2017/04/10/django-csrf-with-axios/

If someone is strugling with axios to make this work this helped me:

import axios from 'axios';

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'

Source: https://cbuelter.wordpress.com/2017/04/10/django-csrf-with-axios/


回答 16

在我的情况下,问题出在我将nginx配置从主服务器复制到一个临时的服务器,并禁用了第二个服务器上不需要的https。

我必须在配置中注释掉这两行以使其再次起作用:

# uwsgi_param             UWSGI_SCHEME    https;
# uwsgi_pass_header       X_FORWARDED_PROTO;

In my case the problem was with the nginx config that I’ve copied from main server to a temporary one with disabling https that is not needed on the second one in the process.

I had to comment out these two lines in the config to make it work again:

# uwsgi_param             UWSGI_SCHEME    https;
# uwsgi_pass_header       X_FORWARDED_PROTO;

回答 17

这是Django提供的较为简单的解决方案:

<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// set csrf header
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

// Ajax call here
$.ajax({
    url:"{% url 'members:saveAccount' %}",
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
        alert(data);
        }
    });
</script>

来源:https : //docs.djangoproject.com/en/1.11/ref/csrf/

Here’s a less verbose solution provided by Django:

<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// set csrf header
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

// Ajax call here
$.ajax({
    url:"{% url 'members:saveAccount' %}",
    data: fd,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(data) {
        alert(data);
        }
    });
</script>

Source: https://docs.djangoproject.com/en/1.11/ref/csrf/