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

时间:2019-05-31 12:18:50

标签: node.js reactjs express axios csrf

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

有什么想法吗?

谢谢

0 个答案:

没有答案