express.js CSURF cookie和标头匹配,返回403 [英] express.js CSURF cookie and header match, returning 403
问题描述
我有一个简单的快速服务器设置,例如:
I have a simple express server setup like:
app.use(bodyParser.json());
app.use(cookieParser());
app.use(csurf({ cookie: true }));
// routes
app.use(Routes imported from another file);
客户端当前只是一种简单的反应形式。我在React应用程序加载之前已经加载了一些初始数据,并且在那里设置了csrf cookie。
The client is currently just a simple form in react. I am loading some initial data before the react app loads and the csrf cookie is being set there.
我有一个简单的函数来解析csrf cookie客户端。我要在create-react-app中代理快递服务器,所以我不能只在标头中设置元标记。
I have a simple function for parsing the csrf cookie client side. I'm proxying the express server in create-react-app so I can't just set a meta tag in the header.
const csrfToken = () => {
const cookies = decodeURIComponent(document.cookie).split(';');
const token = cookies.find(cookie => cookie.includes('_csrf'));
if (token) {
return token.split('=')[1]
}
}
我正在使用访存来发送数据和令牌
I am using fetch to send along data and the token
const response = await fetch(url, {
credentials: 'include',
method: 'POST',
headers: {
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken()
},
body: JSON.stringify({ ...body })
});
我尝试注释掉告诉应用程序使用csurf的行并检查是否存在所有内容根据要求。我可以验证Cookie和标头在我发送的每个请求中是否匹配。一切似乎都正确,但是我仍然遇到403错误,因此我必须丢失某些内容。我茫然不知所措,我发现谷歌搜索就是其他人也非常相似地设置他们的应用。
I've tried commenting out the line that tells the app to use csurf and checking that everything is present on the request. I can verify that the cookie and the header are matching in every request I send. Everything seems correct, but I am still getting a 403 error so I must be missing something. I'm at a lost to what it could be and all I could find googling is other people setting up their apps very similarly.
推荐答案
您正在读取 _csrf
cookie的内容,并将其发送回 X-CSRF-Token
标头内。
You are reading the content of the _csrf
cookie and sending it back inside X-CSRF-Token
header. This will not work.
在Express中运行的 csurf
中间件已由以下代码配置: app.use(csurf({cookie:true}));
生成 _csrf
cookie并将其发送给客户端。中间件希望您:
The csurf
middleware running inside Express has been configured by this code: app.use(csurf({ cookie: true }));
to generate the _csrf
cookie and send it to the client. The middleware expects you to:
- 在服务器上生成第二条CSRF数据。
- 将第二条数据附加到发送给客户端的响应中。结果,响应将同时带有
_csrf
cookie和附加的第二条数据到达客户端。 - 确保传入来自客户端的请求具有相同的
_csrf
cookie,并且第二条数据被复制到六个预定义的位置/位置之一(例如 X-CSRF-Token标头或
- Generate the second piece of CSRF data on the server.
- Attach the second piece of data to the response sent to a client. As a result, the response arrives to the client with both the
_csrf
cookie and the second piece of data attached. - Ensure the incoming request from the client has the same
_csrf
cookie and the second piece of data copied into one of the six predefined places/locations (such as 'X-CSRF-Token' header or another location).
请参见此回答以获取更多详细信息。
See this answer for more details.
这篇关于express.js CSURF cookie和标头匹配,返回403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!