首页 > 解决方案 > 即使我没有在 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;

标签: reactjsexpressaxioscsrfcsrf-token

解决方案


X-XSRF-TOKEN在我的反应应用程序中由 Axios 在请求标头中自动设置和发送,这就是为什么当我没有设置 _csrf 令牌时它仍然有效。但是在邮递员中,它不起作用,这就是为什么我需要在正文中手动添加 _csrf 令牌。


推荐阅读