Javascript JQuery + AJAX + Django = CSRF ?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7214909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:22:34  来源:igfitidea点击:

JQuery + AJAX + Django = CSRF ?

javascriptajaxdjangocsrf-protection

提问by Krzysztof Trzos

Possible Duplicate:
"CSRF token missing or incorrect" while post parameter via AJAX in Django

可能的重复:
在 Django 中通过 AJAX 发布参数时“CSRF 令牌丢失或不正确”

I wanted to send login data by AJAX to authenticate user, but it wasn't possible because of CSRF. Could You tell me what to add to my code to make it woking?

我想通过 AJAX 发送登录数据来验证用户身份,但由于 CSRF,这是不可能的。你能告诉我在我的代码中添加什么才能使它工作吗?

my JavaScript file:

我的 JavaScript 文件:

$("#login").live("click", function() {
    var username = $(".login_username").val();
    var password = $(".login_password").val();

    $.ajax({
        url: "/login",
        type: "POST",
        data: {
            username: username,
            password: password
        },
        cache: false,
        success: function(tekst) {
            alert(tekst);
        }
    });
});

采纳答案by Arnaud Le Blanc

There is a method explained here.

这里解释了一种方法

It consists of adding a X-CSRFToken header on each ajax request.

它包括在每个 ajax 请求上添加一个 X-CSRFToken 标头。

This is done by hooking in the jQuery.ajaxSend event, so everything is done automatically (you just have to copy and past their code, and run it once before the first ajax request you make).

这是通过挂钩 jQuery.ajaxSend 事件来完成的,所以一切都是自动完成的(您只需复制并粘贴他们的代码,并在您发出第一个 ajax 请求之前运行一次)。

回答by ElHacker

I've been trying to solve the same problem, And as arnaud576875 says you have to Add the csrf token header on each ajax request just like the Django docs says https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajaxAnd execute that code before any Ajax request you make.

我一直在尝试解决同样的问题,正如 arnaud576875 所说,你必须在每个 ajax 请求上添加 csrf 令牌标头,就像 Django 文档所说的https://docs.djangoproject.com/en/dev/ref/contrib /csrf/#ajax并在您发出任何 Ajax 请求之前执行该代码。

But there is something additional, you have to find a way to load the csrf token to the cookies of your app before trying to do any AJAX request, after a lot of painful hours researching I couldn't find an specific answer of how to do this, what I did found is that to ensure that your view sends the csrf token within a cookie you can use the ensure_csrf_token()to each view you want to receive the token https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookiethis seems to work for a lot of people, but did not worked for me.

但是还有一些额外的东西,在尝试执行任何 AJAX 请求之前,您必须找到一种方法将 csrf 令牌加载到应用程序的 cookie 中,经过大量痛苦的研究,我找不到具体的答案这个,我发现的是,为了确保您的视图在 cookie 中发送 csrf 令牌,您可以将其ensure_csrf_token()用于您想要接收令牌的每个视图https://docs.djangoproject.com/en/dev/ref/contrib /csrf/#django.views.decorators.csrf.ensure_csrf_cookie这似乎对很多人有用,但对我没用

Another way is using the Legacy Method, adding the 'django.middleware.csrf.CsrfResponseMiddleware' to your MIDDLEWARE_CLASSESbut I don't recommend this method because leaves several security risks. https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method

另一种方法是使用 Legacy Method,将其添加'django.middleware.csrf.CsrfResponseMiddleware' 到您的MIDDLEWARE_CLASSES但我不推荐这种方法,因为会留下一些安全风险。 https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method

All this methods that I said before did not worked for me. The way that I'm allowing Ajax to do some requests is as the following, and if someone finds this a dangerous method please let me know:

我之前说的所有这些方法对我都不起作用。我允许 Ajax 执行一些请求的方式如下,如果有人发现这是一种危险的方法,请告诉我:

  1. Go to the first view that your user will hit, like the /home/ page.
  2. Insert this before redirecting or parsing anything request.META["CSRF_COOKIE_USED"] = True
  1. 转到您的用户将点击的第一个视图,例如 /home/ 页面。
  2. 在重定向或解析任何内容之前插入 request.META["CSRF_COOKIE_USED"] = True

And that's it, That is the way that works for me, but as I said before I'm not sure if this is the right method or the most secure one to accomplish the csrf protection.

就是这样,这是对我有用的方式,但正如我之前所说,我不确定这是否是完成 csrf 保护的正确方法或最安全的方法。