简体   繁体   中英

Express and React, send CSURF token

I have a NodeJs server running some app using EJS, now I want to add a React app.

But I don't quite manage to send the csrf token back to the server from React.

Here's my server setup:

const csrfMiddleware = csurf({
  cookie: true,
});
app.use(csrfMiddleware);

Here I'm trying to send it from the frontend:

 let _csrf = cookie.load("_csrf");
      const config = {
        headers: {
          "CSRF-Token": _csrf,
          "Content-Type": "application/json",
        },
      };

But this doesn't work, I get ForbiddenError: invalid csrf token . How am I supposed to get the csrf without breaking the current server functionality?

Thanks in advance

I tried figuring it out myself, don't know if it's the best option (probably not), but this is what worked for me.

server:

app.get("/getcsrf", (req, res) => {
  res.json({ _csrf: req.csrfToken() });
});

React:

 const { data: csrfData } = await axios.get("/api/campaign/getcsrf");
     

What I did was, add a route on the server, to get the generated csrf token.

and fetch it on the client-side when needed.

2 problems:

  1. need to call this before every post-request
  2. don't know how secure it is.

but at least it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM