我正忙于开发一个React Native应用程序,它可以与Django服务器上的GraphQL应用程序接口进行对话。
在React Native中,我正在使用React Relay尝试并处理我的GraphQL请求(遵循here的指南),但我的请求有403个问题。
回复说,CSRF token missing or incorrect和我正在努力找出最好的方法来让它工作。
我知道我需要首先获得一个CSRF cookie令牌,然后以某种方式将它与我的GraphQL Post请求一起传递,但没有太多幸运。我目前的实现如下所示...
fetch('http://' + ip + ':8000/sign-in/')
.then((response) => {
const cookieHeader = response.headers.map["set-cookie"]; // This gets me a cookie response with a CSRF token
fetch('http://' + ip + ':8000/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookieHeader, // Try and pass the received cookie to my POST
'XSRF-TOKEN': cookieHeader // Trying this as well
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
console.log('RESPONSE', response) // Currently getting a 403
return response.json()
})
})但是这仍然会得到一个403错误。
我似乎找不到更多关于如何处理这个问题的信息。有没有人能告诉我哪里出了问题,或者有没有其他方法的建议?
(下面是我的API请求的快照)

发布于 2018-01-17 20:16:20
所以我设法让它和下面的代码一起工作。
return getCsrfToken().then(csrfToken => {
if (csrfToken == null) {
console.log('CSRF NOT SET')
}
const url = 'http://' + ip + '/graphql'
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify({
query: operation.text,
variables,
}),
})
.then(response => {
return response.json()
})
.catch(error => {
console.log('POST ERROR', error)
})
});
function getCsrfToken() {
var url = 'http://' + ip + '/graphql';
return CookieManager.get(url).then(response => {
return response.csrftoken;
});
}发布于 2018-03-24 04:26:26
添加这个是因为这是我在使用Django + GraphQL的中继进行CSRF故障排除时发现的最具体的问题
即使我发布了CSRF令牌,我也收到了类似的CSRF错误响应。我必须添加fetch头来匹配我的Django后端的安全设置。在本例中,我是浏览器中的Relay,因此我从cookie中获取CSRF令牌。
我已经关注了CSRF with AJAX in cookies的Django文档。由于我的安全设置,我必须添加“同源”凭证。我将在Relay快速入门教程中标注我必须更改的几项内容
import { get as getCookie} from 'browser-cookies'
return fetch('/graphql/', { // Added the trailing slash here
method: 'POST',
credentials: "same-origin", // Added this line
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken'), // getting token from cookies
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
return response.json();
});这就是为我解决这个问题的方法。
https://stackoverflow.com/questions/48145681
复制相似问题