Can't verify CSRF token authenticity Rails/React

robinmanz picture robinmanz · Feb 21, 2019 · Viewed 8k times · Source

I have a react component in my rails app where I'm trying to use fetch() to send a POST to my rails app hosted on localhost, this gives me the error:

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

I'm using devise gem to handle user/registrations and logins.

I have tried to remove protect_from_forgery with: :exception

Here is the code for my fetch,

this.state.ids.sub_id});
  fetch(POST_PATH, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: body  
  }).then(res => res.json()).then(console.log);

How can I get the csrf token and send it through the form so that it will pass?
Ideally I would like to just send it through the headers but I have no idea how to access the token.

Answer

HermannHH picture HermannHH · Feb 21, 2019

The simplest way to do this, if you are merely embedding a react component in your Rails view, is to retrieve the csrf token from your rails view and then pass it as a header in your fetch api call.

You can get the csrf token by doing something like this:

const csrf = document.querySelector("meta[name='csrf-token']").getAttribute("content");

And then you just pass it as a header in your fetch call: ... headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrf }, ...

I normally don't use fetch, so not too sure about the exact syntax, but this should help guide you.