问题描述
我得到令牌CSRF丢失或不正确的错误,而从我的本地机器做一个POST请求到远程的Django API。
我在AngularJS设置:
的.config(['$ httpProvider',函数($ httpProvider){$ httpProvider.defaults.xsrfCookieName ='csrftoken';
$ httpProvider.defaults.xsrfHeaderName ='X-CSRFToken';}]);
但IM仍然得到的 CSRF令牌丢失或不正确错误
我检查正在发送什么头,显然角不发送 HTTP_X_CSRFTOKEN
。
但我可以看到该Cookie csrftoken =东西被发送。
有谁知道这是怎么回事?
请求头
POST / S /登录/ HTTP / 1.1
主持人:server.somewhere.io:8000
连接:保持活动
内容长度:290
编译:无缓存
缓存控制:无缓存
接受:应用/ JSON,纯文本/ * / *
产地:HTTP://本地主机
用户代理:Mozilla的/ 5.0(Windows NT的6.1; WOW64)为AppleWebKit / 537.36(KHTML,像壁虎)的Chrome / Safari浏览器48.0.2564.116 / 537.36
内容类型:应用程序/ JSON的;字符集= UTF-8
引用者:HTTP://本地主机/ thesocialmarkt /
接受编码:gzip,紧缩
接受语言:EN-GB,EN; Q = 0.8,EN-US; Q = 0.6,PT-BR; Q = 0.4,PT; Q = 0.2
饼干:csrftoken = hiYq1bCNux1mTeQuI4eNgi97qir8pivi;的SessionID = 1nn1phjab5yd71yfu5k8ghdch2ho6exc
由于@克里斯霍克斯指出,这个计算器由@Ye刘给出的答复
I verified that as long as you don't make http get request, csrftoken
cookie doesn't get set. So only
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
would not work. You first need to make if not real then mock http get request to django rest_framework
.
Update: Your comments pushed me to further study it, Please read this blog where is has mentioned as,
So lets try with this single request first.
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
where you are injecting $cookies
to the controller/service.
If it works then may be writing interceptors
would be good choice, and would help you to debug as well.
I am sure you are using AngularJs version at least 1.2, See this changesetand in recent commit Angular http service checking csrf with this code,
var xsrfValue = urlIsSameOrigin(config.url)
? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
So it's necessary that you are sending same token which is present in cookie.
Further to analyse use developer tool of your browser to see request/response with the http request and analyse headers and cookies.
这篇关于CSRF令牌丢失或不正确。 Django的+ AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!