Csrf 验证失败 - Django Rest 和 Backbone.js

Csrf verification failed - Django Rest and Backbone.js

我已经开始 "Lightweight Django" https://github.com/lightweightdjango to learn more about Django and Client-Side JavaScript. During testing out the LoginView created using Backbone.js I get the Forbidden(403) CSRF verification failed.Request aborted. message, as pointed out in this post: CSRF verification failing in django/backbone.js 了。 首先,我想在表单中插入 {% csrf_token %} 模板标签,但是当我这样做时,服务器给我一条 POST / HTTP/1.1" 405 0 - Method Not Allowed (POST) : / 消息。

由于 AJAX X-CSRFToken 请求 header 是使用 $.ajaxPrefilter() 设置的,我不知道问题出在哪里。

当我使用 httpie 使用超级用户详细信息执行 POST 请求时,一切正常,如下例所示:

 HTTP/1.0 200 OK
 Allow: POST, OPTIONS
 Content-Type: application/json
 Date: Mon, 11 Sep 2017 13:49:49 GMT
 Server: WSGIServer/0.2 CPython/3.6.2
 Vary: Cookie
 X-Frame-Options: SAMEORIGIN

 {
    "token" : some_value
 }

使用 "Inspect Element" 功能中的控制台,我收到以下消息:

 Response headers:
   Allow: GET, HEAD, OPTIONS
   Content-Length: 0
   Content-Type: text/html; charset=utf-8
   Date: Mon, 11 Sep 2017 14:03:06 GMT
   Server: WSGIServer/0.2 CPython/3.6.2
   X-Frame-Options: SAMEORIGIN

 Request headers:
   Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
   Accept-Encoding: gzip, deflate
   Accept-Language: en-US,en;q=0.5
   Connection: keep-alive
   Content-Length: 116
   Content-Type: application/x-www-form-urlencoded
   Cookie: csrftoken=some_value
   Host: 127.0.0.1:8000
   Referer: http://127.0.0.1:8000/
   Upgrade-Insecure-Requests: 1
   User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0

我不知道是 TemplateView 造成的还是我遗漏了什么:

 urls.py:    
   from django.conf.urls import url,include
   from django.views.generic import TemplateView
   #from django.views.decorators.csrf import ensure_csrf_cookie

   from rest_framework.authtoken.views import obtain_auth_token

   from board.urls import router

   urlpatterns = [
       url(r'^api-auth/', obtain_auth_token, name='api-login'),
       url(r'^api-root/', include(router.urls)),
       url(r'^$', TemplateView.as_view(template_name='board/index.html')),
   ]

有人可以解释一下到底发生了什么吗? 谢谢!

对于每个 POST 请求,您需要将 CSRF 令牌发送到 Django weebasite 中的 django 后端,您可以为您的前端罚款 ajaxSetup (backbone.js)。只需创建新文件 ajaxSetup.js 并通过此代码即可。

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
    // test that a given url is a same-origin URL
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + 
    '/') ||
    (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + 
    '/') ||
    // or any other URL that isn't scheme relative or absolute i.e relative.
    !(/^(\/\/|http:|https:).*/.test(url));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
            // Send the token to same-origin, relative URLs only.
            // Send the token only if the method warrants CSRF protection
            // Using the CSRFToken value acquired earlier
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

你可以在django官方网站上看到这个CSRF TOKEN