通过API请求POST时CSRF验证失败 [英] Got CSRF verification failure when while requesting POST through API

查看:495
本文介绍了通过API请求POST时CSRF验证失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用REST API编写网站.我在后端使用带有活塞的django(也使用了带有CORS_ORIGIN_ALLOW_ALL = True的corsheaders.middleware.CorsMiddleware).而且我将ebrian.js用于前端.我正在从客户端发送POST请求并收到错误消息:

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.js for frontend. I'm sending POST request from client-side and get error:

CSRF verification failed. Request aborted.

我在Google上搜索了很多,所有解决方案都建议使用使用自动添加RequestContext的呈现快捷方式"之类的方法.但是我不认为,表单会从前端请求,这不应该知道后端是如何工作的.这是我的密码

I've googled a lot and all solutions suggested something like "Use the render shortcut which adds RequestContext automatically". But I have no view, forms will be requested from frontend, that shouldn't know about how backend works. Here's code of my scipt

Question = Backbone.Model.extend({
    urlRoot: 'http://example.com/api/questions',

    defaults: {
        id: null,
        title: '',
        text: ''
    },

    initialize: function() {
        //alert(this.title);
    }
});

var question2 = new Question;
var questionDetails = {title: 'test title', text: 'test text'};
question2.save(questionDetails, {
    success: function(question) {
        alert(question.toJSON());
    }
});

推荐答案

django文档提供了有关如何设置jquery以通过ajax发送csrf令牌的说明.

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

您应该确保模板标签{% csrf_token %}在前端中呈现了某些内容.这样,您就知道令牌已被创建并传递给前端.如果您按照上述文档中的说明进行操作,那么您的csrf令牌应始终与ajax请求一起发送.这是我的一个网站的javascript外观(假设您使用的是jQuery).

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

此外,请确保您的MIDDLEWARE_CLASSES设置中包含'django.middleware.csrf.CsrfViewMiddleware'.

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

这篇关于通过API请求POST时CSRF验证失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆