Do i have to use csrf protection in React SPA? Do i have to use csrf protection in React SPA? express express

Do i have to use csrf protection in React SPA?


So do I need CSRF?

As stated here: Am I under risk of CSRF attacks in a POST form that doesn't require the user to be logged in? I think you should still set it.

As for why it is not working for you, I assume it is because of the header name. You may check what CSURF checks by default.

The default value is a function that reads the token from the following locations, in order:

  • req.body._csrf - typically generated by the body-parser module.
  • req.query._csrf - a built-in from Express.js to read from the URL query string.
  • req.headers['csrf-token'] - the CSRF-Token HTTP request header.
  • req.headers['xsrf-token'] - the XSRF-Token HTTP request header.
  • req.headers['x-csrf-token'] - the X-CSRF-Token HTTP request header.
  • req.headers['x-xsrf-token'] - the X-XSRF-Token HTTP request header.

Going by what CSURF checks, you have a variety of options to choose from, and looking at axios, it seems to have a couple options for setting xsrf cookie and header names.

...// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default...

For example, in order to use the X-XSRF-TOKEN header key axios comes with by default, I used the following method in my App.js file:

componentDidMount() {    axios.get(`/api/csrf`) // Send get request to get CSRF token once site is visited.      .then(res => {        axios.defaults.headers.post['X-XSRF-TOKEN'] = res.data; // Set it in header for the rest of the axios requests.      })  }

You could, however, use a form hidden input or any other method you're comfortable with. You can read more about why it's common to put them in cookies here.

I'm not sure what you're using for your client, but if you're using Redux, you may look here for help. If it doesn't work, you may Google other methods.