问题描述
嗨,我正在尝试在 react js 和 express js 应用程序中实现 CSRF 保护。 express api 与邮递员一起正常工作,当我将 _csrf : token 与 req.body 附加时,它会工作,否则它会抛出无效的 csrf 令牌。那是完美的。但是当我使用 axios 从 react 应用程序调用 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 在我的 React 应用程序中自动设置并由 Axios 在请求标头中发送,这就是为什么当我没有设置 _csrf 令牌时它仍然有效.但是在邮递员中,它不能那样工作,这就是为什么我需要在正文中手动添加 _csrf 令牌。