Got CSRF verification failure when while requesting POST through API

前端 未结 2 792
一向
一向 2021-01-28 12:48

I\'m writing a site using REST API. I use django with piston at backend (also using corsheaders.middleware.CorsMiddleware with CORS_ORIGIN_ALLOW_ALL = True). And I use backbone.

2条回答
  •  醉话见心
    2021-01-28 13:28

    The django docs have instructions on how to set up jquery to send the csrf token via ajax.

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

    You should make sure that the template tag {% csrf_token %} renders something in your frontend. That way you know that the token is being created and passed to the frontend. If you follow the instructions from the docs above then your csrf token should always be sent with ajax requests. This is what the javascript looks like for one of my sites (assuming you are using jQuery).

    // Set up Django CSRF Token Protection
    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;
    }
    var csrftoken = getCookie('csrftoken');
    
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    

    Also, make sure that 'django.middleware.csrf.CsrfViewMiddleware' is in your MIDDLEWARE_CLASSES settings.

提交回复
热议问题