Django Rest Framework,CSRF和Vue.js [英] Django Rest Framework, CSRF and Vue.js

查看:70
本文介绍了Django Rest Framework,CSRF和Vue.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Vue.js对我使用Django Rest Framework创建的REST Api进行一些POST方法。问题是,我收到 CSRF失败:CSRF令牌丢失或不正确。发布时出错。但是我可以看到csrf cookie,并且它已被添加到标题中。

I'm trying to use Vue.js to do some POST methods to my REST Api that I created with Django Rest Framework. Problem is, I'm getting the CSRF Failed: CSRF token missing or incorrect. error when I post. But I can see the csrf cookie, and it's being added to the headers.

这是我的设置:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
        'rest_framework.permissions.DjangoModelPermissions'
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication'
    )
}

这是我的Vue.js配置:

Here's my Vue.js config:

var csrftoken = Cookies.get('csrftoken');
Vue.http.headers.common['HTTP_X_CSRFTOKEN'] = csrftoken;

这是发送的标头的相关部分:

And here's the relevant part of the headers that were sent:

Cookie:djdt=hide; tabstyle=raw-tab; sessionid=1gl533mrneudxw3l9l2vg0ja1yowwmeo; csrftoken=dN85bhztB1oVRov87BsUrWTM29Ff9sjn
Host:127.0.0.1:8000
HTTP_X_CSRFTOKEN:dN85bhztB1oVRov87BsUrWTM29Ff9sjn
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/agencies/6/add-profiles/

如您所见,Cookie.csrf和HTTP_X_CSRFTOKEN标头匹配

As you can see, Cookie.csrf and the HTTP_X_CSRFTOKEN header match

我真的很沮丧。有建议吗?

I'm really stumped. Any suggestions?

推荐答案

所以我将其发布为答案以结束问题。

So I'm posting this as an answer to close the question.

问题是由于根据请求发送的CSRF标头名称错误。根据文档:

The issue was because of the wrong CSRF header name that was sent on request. According to documentation:


与request.META中的其他HTTP标头一样,从服务器收到的标头名称
由将所有字符转换为大写的
,用下划线替换所有连字符,然后在名称中添加
'HTTP_'前缀。例如,如果您的客户端发送
'X-XSRF-TOKEN'标头,则设置应为'HTTP_X_XSRF_TOKEN'。

As with other HTTP headers in request.META, the header name received from the server is normalized by converting all characters to uppercase, replacing any hyphens with underscores, and adding an 'HTTP_' prefix to the name. For example, if your client sends a 'X-XSRF-TOKEN' header, the setting should be 'HTTP_X_XSRF_TOKEN'.

我还要在这里留下对我的问题,它累积了一些可能导致 CSRF失败的问题:CSRF令牌丢失或不正确。 Django中的错误。

Also I'm leaving here a reference to my question, which accumulates several problems that may lead to CSRF Failed: CSRF token missing or incorrect. error in Django.

这篇关于Django Rest Framework,CSRF和Vue.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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