问题
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);
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.
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 })
});
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.
回答1:
You are reading the content of the _csrf
cookie and sending it back inside X-CSRF-Token
header. This will not work.
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:
- 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.
来源:https://stackoverflow.com/questions/59606019/express-js-csurf-cookie-and-header-match-returning-403