【发布时间】:2021-08-29 05:16:57
【问题描述】:
我正在使用 react-native 移动应用程序中的以下代码对 dj-rest-auth 本地链接进行社交身份验证调用。但是,我的 Facebook 身份验证每次都成功,然后执行 fetch(或 axios)本地 API 调用,它第一次完美运行/运行返回令牌,但此后在其他所有运行中,它给我一个错误,说缺少或无效 csrf令牌。我不能使用 Django docs getCookie 函数,因为它给出了 Document 错误,因为这是一个 react-native 移动应用程序。请指导如何使用移动应用程序中的 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))
logout函数也给出了缺失或无效的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))
}
【问题讨论】:
-
这能回答你的问题吗? get csrf token in react native
-
@VasylNahuliak 不。该问题不使用 django rest auth。对于 Django rest auth,如果您再次删除 csrf,您将得到相同的 csrf 丢失或无效错误。无论如何,我的代码是第一次运行,这可能意味着 csrf 令牌已成功发送到 django 服务器。但问题在于剩余的进一步调用。
-
如果你真的需要 csrf 令牌,你可以尝试使用这个 sn-p gist.github.com/jqn/e6a2073e26f5db90a55664f53a1fcbad 和 github.com/react-native-cookies/cookies 从 cookie 中获取它们
-
@VasylNahuliak 谢谢。我看过 react-native cookie 的 github 链接。他们提到他们不支持 Expo,因为它使用自己的 cookie 支持和给定的链接:github.com/expo/expo/issues/6756。我现在遇到了死锁问题,因为世博会问题仍未解决。
标签: react-native django-rest-framework csrf fetch-api django-rest-auth