问题描述
在过去的三天里,我被这个问题困住了,这让我非常沮丧。我不知道还能尝试什么。
我在 localhost:1337 上运行 Sails 应用程序,在 localhost:3000 上运行 create-react-app。
我在后端启用了 csrf 并按照 the sails documentation 来实现它。 我已经创建了路线 'GET /grant-csrf-token': { action: 'security/grant-csrf-token' } 并且它工作正常,我得到了令牌。如果我使用邮递员,则接受令牌并且我的登录表单有效。
然而,在 React 中,我收到了令牌,但在提交登录请求时出现 403 Forbidden 错误。
useEffect(async () => {
let csrftoken;
try {
let csrftokenRequest = await Axios.get(
`${state.serverUrl}/grant-csrf-token`
);
csrftoken = csrftokenRequest.data["_csrf"];
dispatch({
type: "csrf",value: csrftoken,});
} catch (err) {
dispatch({
type: "flashMessage",value: "There was an error.",});
}
},[]);
我尝试了各种方法来通过我的帖子请求发送令牌:
await Axios.post(
`${appState.serverUrl}/login`,{
emailAddress,password,_csrf: appState.csrf,},{ withCredentials: true }
);
Axios.defaults.headers.post["X-CSRF-Token"] = appState.csrf;
并将 cors allowRequestHeaders 参数设置为 allowRequestHeaders: 'content-type,X-CSRF-Token',
我也尝试将其作为查询参数发送
`/login?_csrf=${encodeURIComponent(appState.csrf)}`
我也在 Sails 中尝试了各种 cors 设置,目前它是这样设置的:
cors: {
allRoutes: true,allowOrigins: [
'http://localhost:3000',],allowCredentials: true
}
再次澄清一下:
- /grant-csrf-token 路由工作正常。我收到令牌
- 它适用于 Postman
- 在 React 中我收到 403 错误
解决方法
你能不能试试这样的:
在标头中发送 csrf 并允许 Sails 处理请求标头。
// config/security.js
cors: {
allRoutes: true,allowOrigins: ['http://localhost:3000'],allowCredentials: true,allowRequestHeaders: ['content-type','x-csrf-token','authorization'],},