且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django DRF-如何使用令牌身份验证进行CSRF验证

更新时间:2021-10-25 06:49:29

当我开始将Angular 1.x与Django和DRF一起使用时,我遇到了同样的问题,然后我发现了这段代码我认为是一本书的摘要,对我来说很好。在导入任何JavaScript之前,将此文件包含在您的 base.html 文件或主html文件中,一切将顺利进行,您可以开始与后端进行对话了。

I've got the same problem when i started to use Angular 1.x with Django and DRF, and then i found this code snippet in a book i think, and it works fine for me. Include this file in your base.html file or your main html file before any javascript import, and everything will work smoothly and you can start talking to your backend.

// Place at /static/js/csrf.js
// CSRF helper functions taken directly from Django docs
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({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});