msmith1114
msmith1114

Reputation: 3229

Rails 6 `protect_from_forgery with: :null_session` not working

In an effort to learn React and using Rails together I am in the process of building a simple "Todo" app. Im using axios to make requests to my rails api within react components.

So far everything was working fine until I made my first POST request. Im pointing to the right place and sending fine params but saw I was getting Can't verify CSRF token authenticity.. Upon further googling it appears that adding:

class ApplicationController < ActionController::Base
    protect_from_forgery with: :null_session
end

Would fix my issue. But despite server restarts/etc... I still receive the same error when sending a POST request. Also adding prepend: true does not help either (as was suggested by another member).

Is there something im missing? This seems like a straightforward problem from what i've read but it doesn't seem to be working for me.

Im on Rails 6.0

Upvotes: 3

Views: 3552

Answers (1)

Les Nightingill
Les Nightingill

Reputation: 6156

if you just want the error to go away, use:

class ApplicationController < ActionController::Base
  skip_forgery_protection
end

But if you would like to actually take advantage of the Rails forgery protection, then add an "X-CSRF-Token" header to your post request from React. The value for this header can be retrieved by javascript from the page's head element, in a meta tag included by Rails. For example (using jQuery):

var csrf_token_value = $('meta[name="csrf-token"]').attr('content')

Upvotes: 6

Related Questions