【问题标题】:django csrf token : CSRF token missing or incorrectdjango csrf 令牌:CSRF 令牌丢失或不正确
【发布时间】:2021-07-14 10:34:52
【问题描述】:

我不使用 django 表单,我们只使用 API 处理它并响应结果。 我想在不使用@csrf_exempt 的情况下处理它。 在使用表单的时候,我知道你在使用标签,但是在这种情况下,很难写标签。我无法摆脱 csrf 所以我需要帮助。 收到作为帖子的请求时,“CSRF 令牌丢失或不正确”。出现。我该如何解决这个问题?

【问题讨论】:

    标签: python django csrf


    【解决方案1】:

    如果您需要 csrf 令牌,请查看 csrf doc

    您可以将给定的代码添加到全局 js 文件中,然后在任何地方引用它。我在这里包含代码,但在文档中是相同的。

    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // 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;
    }
    

    然后获取csrf令牌:

    const csrftoken = getCookie('csrftoken');
    

    这是我如何在 fetch 中使用它的示例:

    fetch('some_url', {
            method: 'POST',
            headers:{
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRFToken': csrftoken,
        },
            body: JSON.stringify({
                some_key: some_var,
                ...
            })
        })
        .then(response => {
            jsonResponse = response.json();
            status_code = response.status;
    
            if(status_code != 200) {
                
                alert('error');
            } else {
                alert('success');
            }
        })
        .catch(error => {
            console.log(error)
        })
    

    但是通过包含 csrf 模板标签 {% csrf_token %} 来确保 csrf 令牌在您的模板中可用

    【讨论】:

      【解决方案2】:

      如果这是一个无状态 API(即您不使用 cookie),您可以安全地禁用 CSRF,如下所示:

      from django.views.decorators.csrf import csrf_exempt
      
      @csrf_exempt
      def post(request):
          return 'page'
      

      【讨论】:

        猜你喜欢
        • 2021-11-13
        • 2012-04-20
        • 2012-09-25
        • 1970-01-01
        • 1970-01-01
        • 2014-12-25
        • 2016-05-12
        • 2016-06-10
        • 2017-09-14
        相关资源
        最近更新 更多