本文介绍了Django DRF-如何使用令牌身份验证进行CSRF验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django和Django Rest Framework开发REST API。
在前端,我有AngularJs应用程序。
我已经对API使用令牌认证。这会禁用CSRF检查。

I am working on REST API using Django and Django Rest Framework.In the front-end I have AngularJs app.I have used Token authentication for APIs. This disables the CSRF checks.

我想保持REST API进行CSRF验证。如何实现此目标?

I want keep CSRF validation with REST API. How to achieve this ?

我应该如何获取CSRF令牌值,以便可以使用我的角度应用程序的拦截器将其设置为每个POST请求的标头中。

How should I get CSRF Token value so that it can be set into the header of every POST request, using interceptor of my angular application.

推荐答案

当我开始将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);
        }
    }
});

这篇关于Django DRF-如何使用令牌身份验证进行CSRF验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:18