reactjs - 即使我没有在 react 应用程序的 req.body 中附加 _csrf,Express csurf 中间件也总是被接受,但 api 按预期在邮递员中工作
问题描述
嗨,我正在尝试在 react js 和 express js应用程序中实现 CSRF 保护。express api 与邮递员一起正常工作,当我将_csrf : 令牌与req.body附加时,它可以工作,否则它会抛出无效的 csrf 令牌。那是完美的。但是当我使用 axios 从反应应用程序调用 api 时,它在没有 csrf 令牌的情况下工作,请帮助。谢谢
这是快递的代码:
const express = require('express')
const cookieParser = require('cookie-parser')
const csurf = require('csurf')
const cors = require('cors')
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors({ origin: true, credentials: true }));
app.use(cookieParser());
app.use(csurf({
cookie: {
httpOnly: true,
maxAge: 30//30 seconds
}
}));
app.use((req, res, next) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
//do some operation (this should be csrf protected )
//its protected in postman but not in my react app
app.post('/post', authMid, (req, res) => {
console.log("req.headers - ", req.headers['x-xsrf-token']);
res.json({ name: "some operation happen" })
});
我的反应代码:
import axios from 'axios'
import { useState } from 'react'
axios.defaults.baseURL = 'http://localhost:2727/' //api base url
axios.defaults.withCredentials = true
//react App componet
function App() {
const [msg, setMsg] = useState("")
const doOperation= async () => {
try {
//i don't attach the XSRF-TOKEN but still the request is successfull
//but its not successfull if the XSRF-TOKEN is not attach in post man.
const res = await axios.post('/post')
console.log(res.data);
setMsg(res.data)
} catch (e) {
setM(e.message)
}
}
return (
<div>
<button onClick={doOperation}>do Operation</button>
<h1>{msg}</h1>
</div>
);
}
export default App;
解决方案
X-XSRF-TOKEN在我的反应应用程序中由 Axios 在请求标头中自动设置和发送,这就是为什么当我没有设置 _csrf 令牌时它仍然有效。但是在邮递员中,它不起作用,这就是为什么我需要在正文中手动添加 _csrf 令牌。
推荐阅读
- data-warehouse - 单价和折扣 - 事实或维度表
- java - 如何从 Windows 10 卸载 OpenJDK13(未显示在控制面板中)?
- typescript - 将一个大抽象类拆分为多个+从它继承
- google-cloud-platform - 如何监控 GCP 节点 IP 地址
- css - 如何避免使用Angular CSS minifier合并媒体查询声明变量?
- javascript - ZXing.NET 从 HTML5 视频中解码 PDF417 条码
- windows - 在 Windows 8 上运行 rabbitMQ docker 映像时出现问题,其中包含用于保留容器数据的卷
- javascript - 如何向 Vue.js AWS-amplify 应用程序添加身份验证持久性
- html - 另一个元素下方的元素上的 CSS 阴影
- salesforce - SyntaxError: Cannot use import statement outside a module in JEST LWC