'How to implement CSRF protection with csurf in API calls without the use of template engines?

I'm developing a RESTfull API which uses express session and passport.js authentication to store the session in the connect-pg-simple store.

I'm looking into implementing a CSRF protection with the csurf middleware but I haven't found any way of doing it.

In an app using template engines we can implement it like this:

// CSRF
const csurf = require("csurf");
app.use(csurf());

// Register
usersRouter.get("/register", checkAuthenticated, (req, res) => {
  res.render("register", { csrfToken: req.csrfToken() });
});

// EJS
<form action="/users/register" method="POST">
  <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
  <input type="text" id="name" placeholder="Name..." required />
  <button type="submit">Sign Up</button>
</form>

But how can I protect my routes from CSRF attacks in my API without this method?

(I'm basically building the API as a back-end server for my React application)



Solution 1:[1]

Use Express as both React front end and API backend. There are boilerplates for that. The side benefit of this approach is CORS avoidance and therefore better security because there is no need for the backend to send CORS headers that weaken the security.

I'm basically building the API as a back-end server for my React application

That's fine as far as CSRF implementation is concerned and this answer applies to your case. The only difference would be that instead of HTML form mentioned in the answer, you could send the second piece of CSRF data with any response sent by Express in its front end server capacity thus preparing the React app to call an API endpoint (exposed by the same Express server) with both pieces of CSRF data attached to it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 winwiz1