Express csurf 中间件始终被接受,即使我没有在 React 应用程序的 req.body 中附加 _csrf 但 api 按预期在邮递员中工作

Express csurf middleware always accepted even if i don't attach _csrf in the req.body from react app but api works in postman as expected

您好,我正在尝试在 React js 和 express js 应用程序中实现 CSRF 保护。当我附加 _csrf : tokenreq.body 时,快递 api 与邮递员正常工作,否则它会正常工作它抛出无效的 csrf 令牌。那就是 perfect.But 当我使用 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" })
});

我的 React 代码:

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 在我的 React 应用程序中 自动设置并在请求 headers 中发送的为什么当我没有设置 _csrf 令牌时它仍然有效。但是在邮递员中,它不是那样工作的,这就是为什么我需要在 body.

中手动添加 _csrf 令牌的原因