Invalid CSRF Token in React but valid in Postman

I have an Express server on which I'm generating a csrf token. My server looks like this

const csrfProtection = csrf({
  cookie: {
    httpOnly: true,
  },
});
server.use(express.json());
server.use(express.urlencoded({ extended: true }));
server.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
  })
);
server.use(cookieParser());
server.use(csrfProtection);
...
//Other routes

and i'm sending the token like this

export const csrf = (req, res) => {
  return res.send({ csrfToken: req.csrfToken() });
};

If I take it from the response and add it to the X-CSRF-Token header in Postman, then I can access all the routes just fine. But when I do it in React I always get the invalid csrf token error

This is how I take the token in React

export const getCSRFToken = async () => {
  try {
    const { data } = await axios.get("/auth/csrf");
    axios.defaults.headers.post["X-CSRF-Token"] = data.csrfToken;
  } catch (error) {}
};

And I'm using the withCredentials: true flag on other requests. I can't figure out what I'm missing.

2 answers

  • answered 2021-10-20 14:40 ChenLee

    Maybe you should change axios.defaults.headers.post["X-CSRF-Token"] = data.csrfToken to axios.defaults.headers.common["X-CSRF-Token"] = data.csrfToken

  • answered 2021-10-20 14:57 Paul

    Apparently the problem is that you need to pass the withCredetials flag to the request getting the csrf token too. So this fixed the problem.

    export const getCSRFToken = async () => {
      try {
        const { data } = await axios.get("/auth/csrf", { withCredentials: true });
        axios.defaults.headers.common["X-CSRF-Token"] = data.csrfToken;
      } catch (error) {}
    };
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum