ReactJS SPA / Expressjs API,CSURF:ForbiddenError:无效的csrf令牌

问题描述 投票:0回答:1

im试图以ExpressJS作为我的API将csrf令牌集成到我的react-app [SPA]中,这是我的expressjs csurf集成:

...
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use(cookieParser());
app.use(csurf({
    cookie: {
        httpOnly: true,
        domain: `${env.CLIENT_DOMAIN}`, // react-app domain
        path: '/context-csrf',
        secure: process.env.NODE_ENV === 'production',
        maxAge: 3600 // 1-hour
    }
}));
app.use(function (req, res, next) {
    res.cookie('XSRF-TOKEN', req.csrfToken());
    next();
});
app.use(expressValidator())

// here when i integrate my routes

对于我的ReactApp:

axios.get('/context-csrf').then( (response) => {
  axios.defaults.headers.post['X-XSRF-TOKEN'] = response.data._csrf;
  // below line didn't work either
  // axios.defaults.headers.common['X-CSRF-TOKEN'] = response.data._csrf;
  _csrf = response.data._csrf;
});

axios.interceptors.request.use(config => {
  if(config.method === 'post') { config.data._csrf = _csrf; }
  return config;
});

仍然得到ForbiddenError: invalid csrf token

任何想法?

谢谢

node.js reactjs express axios csrf
1个回答
0
投票

您有没有做到这一点。我遇到了类似的问题,但是使用了NestJs和React

© www.soinside.com 2019 - 2024. All rights reserved.