CSRF的小技巧

2018/7/1 posted in  python

django默认开启了CSRF验证,在form的提交或者rest framework里面的POST的请求的时候,会开启CSRF的验证。

如果用户没有登录的情况下,可以不需要使用csrf就调用,但是如果有用户信息的时候,会经过CSRF,在调用请求的时候可以看到相应的返回。

这一篇blog讲的比较清楚 http://www.liujiangblog.com/course/django/179

如果在javascript的代码中修改,需要增加

// using jQuery
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) {
    // 这些HTTP方法不要求CSRF包含
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});