首页 > 解决方案 > Django Ajax CSRF 验证失败

问题描述

这是我的课程,从from django.views.generic import View

class ClassView(ProtectedView, View):

    def __init__(self): 
        self.client = get_default_client()

    def get(self, request, item_remove, item_replacement):
        ... code ...
        return JsonResponse(data)

    def post(self, request, item_remove, item_replacement):
        ... code ...
        return JsonResponse({})

ProtectedView混音:

@method_decorator(login_required, name='dispatch')
@method_decorator(superuser_required, name='dispatch')
class ProtectedView(object):
    def dispatch(self, *args, **kwargs):
        return super(ProtectedView, self).dispatch(*args, **kwargs)

阿贾克斯调用:

        this.utils._ajax({
            method: 'post',
            url: `/api/shortage/${this.item_remove}/${this.item_replacement}`,
            data: {
                item_type: 'product_bundle',
                delivery: productBundles,
            }
        })

阿贾克斯对象:

    _ajax(req) {
        const csrftoken = Cookies.get('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        this.$.ajaxSetup({
            beforeSend: function(xhr, settings) {

                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });

        const ajax$ = this.$.ajax({
            url: req.url,
            dataType: 'json',
            method: req.method,
            data: req.data,
            xhrFields: {
                withCredentials: true
            },
        });

        return ajax$;
    }

请求中的标头

{ 
   'Content-Length':'50',
   'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
   'Host':'localhost:8000',
   'Connection':'keep-alive',
   'Accept':'application/json, text/javascript, */*; q=0.01',
   'Origin':'http://localhost:8000',
   'X-Csrftoken':'QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9',
   'X-Requested-With':'XMLHttpRequest',
   'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Mobile Safari/537.36',
   'Sec-Fetch-Site':'same-origin',
   'Sec-Fetch-Mode':'cors',
   'Referer':'http://localhost:8000/admin/shortage',
   'Accept-Encoding':'gzip, deflate, br',
   'Accept-Language':'en-US,en;q=0.9',
   'Cookie':'csrftoken=QEu0E1GTrbmEfqK9Pv4mB03rliVQAHSmC6p95YOUjZHPJCr8hu42d6cTe3BrTdw9; pnctest=1; logglytrackingsession=37c9453d-1b2c-443d-9a8e-167c8576cb8b; sessionId=68a017ab-a1d5-43a3-93c3-4df44b3851c3; sessionid=zl2k7hwechu0uprq4tqw66znc91op5ua'
}

CSRF Token 显然包含在标头中,但该方法始终返回(403) CSRF verification failed

任何想法来解决这个问题?谢谢。

编辑:由于这部分仍在开发中,我添加@method_decorator(csrf_exempt, name='dispatch')到我的班级继续前进。显然,我不建议将此作为解决方案。

标签: djangoajaxdjango-csrf

解决方案



推荐阅读