“CSRF 令牌丢失或不正确"在 Django 中通过 AJAX 发布参数 [英] "CSRF token missing or incorrect" while post parameter via AJAX in Django

查看:38
本文介绍了“CSRF 令牌丢失或不正确"在 Django 中通过 AJAX 发布参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试发布像

 jQuery.ajax(
        {
            'type': 'POST',
            'url': url,
            'contentType': 'application/json',
            'data': "{content:'xxx'}",
            'dataType': 'json',
            'success': rateReviewResult 
        }
    );

然而,Django返回Forbidden 403.CSRF验证失败.请求中止.我正在使用 'django.middleware.csrf.CsrfViewMiddleware' 并且找不到如何在不影响安全性的情况下防止这个问题.

However, Django return Forbidden 403. CSRF verification failed. Request aborted. I am using 'django.middleware.csrf.CsrfViewMiddleware' and couldn't find how I can prevent this problem without compromising security.

推荐答案

你可以通过两种不同的方式发出 AJAX post 请求:

You can make AJAX post request in two different ways:

  1. 告诉您的视图不要检查 csrf 令牌.这可以通过使用装饰器 @csrf_exempt 来完成,如下所示:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def your_view_name(request):
    ...

  • 要在每个 AJAX 请求中嵌入 csrf 令牌,对于 jQuery,它可能是:

  • To embed a csrf token in each AJAX request, for jQuery it may be:

    $(function () {
        $.ajaxSetup({
            headers: { "X-CSRFToken": getCookie("csrftoken") }
        });
    });
    

    getCookie 函数从 cookie 中检索 csrf 令牌的位置.我使用以下实现:

    Where the getCookie function retrieves csrf token from cookies. I use the following implementation:

    function getCookie(c_name)
    {
        if (document.cookie.length > 0)
        {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1)
            {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
     }
    

    此外,jQuery 有一个插件用于访问 cookie,类似的东西:

    Also, jQuery has a plugin for accessing cookies, something like that:

    // set cookie
    $.cookie('cookiename', 'cookievalue');
    // read cookie
    var myCookie = $.cookie('cookiename');
    // delete cookie
    $.cookie('cookiename', null);
    

  • 这篇关于“CSRF 令牌丢失或不正确"在 Django 中通过 AJAX 发布参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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