2017-09-11 1 views
1

Django 및 클라이언트 측 JavaScript에 대한 자세한 내용은 "Lightweight Django"https://github.com/lightweightdjango을 시작했습니다. 테스트 중에 Backbone.js을 사용하여 생성 된 LoginViewCSRF verification failing in django/backbone.js이라는 메시지에서 Forbidden(403) CSRF verification failed.Request aborted. 메시지를 받았습니다. 우선 서식의 {% csrf_token %} 템플릿 태그 삽입을 생각했지만이 때 서버에서 POST/HTTP/1.1" 405 0 - Method Not Allowed (POST) : / 메시지를 제공합니다.Csrf 확인에 실패했습니다 - Django Rest and Backbone.js

$.ajaxPrefilter()을 사용하여 AJAX X-CSRFToken 요청 헤더가 설정되었으므로 문제가 무엇인지 알 수 없습니다. 나는 수퍼 유저 세부 사항을 사용하여 POST 요청을 수행 할 수 httpie을 사용하고 때

, 다 다음 예제와 같이 잘 작동합니다 : 난을 얻을 "요소 검사"기능에서 콘솔의 사용을 만들기

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 
} 

다음과 같은 메시지 :

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')), 
    ] 
다음 TemplateView 비난하거나 뭔가를 놓치고 경우 나도 몰라

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 

누군가 실제로 일어나는 일을 설명 할 수 있습니까? 감사합니다.

답변

0

모든 POST 요청에 대해 장고 weebasite에서 장고 백엔드로 CSRF 토큰을 보내야합니다. 프론트 엔드 (backbone.js)에 ajaxSetup을 부과 할 수 있습니다. 새 파일 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); 
     } 
    } 
}); 

당신은 장고 공식 웹 사이트에서 이것에 대해 읽을 수 CSRF TOKEN

관련 문제