从React本机获取API调用时出现CSRF问题 [英] csrf issue in fetch API call from react native
本文介绍了从React本机获取API调用时出现CSRF问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用来自原生反应移动应用程序的以下代码对dj-rest-auth本地链接进行社交身份验证调用。然而,我的Facebook身份验证每次都成功,然后Fetch(或axios)本地API调用执行,它在第一次运行时运行得很好,返回令牌给我,但此后每次运行时,它都会给我一个错误,说缺少CSRF令牌或无效。我不能使用Django docs getCookie函数,因为它给出了文档错误,因为这是一个原生的移动应用程序。请指导如何在移动应用程序中正确使用CSRF进行API调用,使用以下代码(在异步函数中):
fetch(
"http://192.168.1.102:8080/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token:resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
注销函数还会给出丢失或无效的CSRF错误,写在下面以供参考:
async function Logout() {
fetch(
"http://192.168.1.102:8080/dj-rest-auth/logout/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken'
}
)
.then(resp => resp.json())
.then(data => {console.log(data)})
.catch(error => console.log(error))
}
推荐答案
通过以下方法解决上述问题:从settings.py中的默认REST身份验证类中删除";会话身份验证,并保持启用";基本身份验证和";令牌身份验证。
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
来源:https://github.com/Tivix/django-rest-auth/issues/164#issuecomment-860204677
这篇关于从React本机获取API调用时出现CSRF问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文