Search code examples
javascriptpythondjangobackbone.js

Csrf verification failed - Django Rest and Backbone.js


I have started going through "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 . First of all I thought of inserting {% csrf_token %} template tag in the form but when I do this the server is giving me a POST / HTTP/1.1" 405 0 - Method Not Allowed (POST) : / message.

Since the AJAX X-CSRFToken request header is being set using $.ajaxPrefilter(), I can't figure out what the problem is.

When I am using httpie to perform POST requests using the superuser details, everything works just fine as in the following example:

 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
 }

Making use of the console from the "Inspect Element" feature I get the following messages:

 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

I don't know if the TemplateView is to blame or I am missing something:

 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')),
   ]

Can someone explain what is actually going on? Thanks!


Solution

  • Fore every POST request you need to send CSRF token to your django backend in Django weebasite u can fined ajaxSetup for your frontend (backbone.js). Just create new file ajaxSetup.js and past this code.

    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);
            }
        }
    });
    

    You can read about this in django official website CSRF TOKEN