Background Details
I am using Devise for authentication to login to a Rails 5 application.
Whenever I bundle either the Audited or Paper Trail gem, when I attempt to #create a new session (via the sign in form - /users/sign_in), I receive the following error:
ActionController::InvalidAuthenticityToken
Environment Details
Ruby 2.3.1
Gems:
Steps to Reproduce:
Another thing to try for anyone running into this is to add the following to your environment configuration file:
config.action_controller.forgery_protection_origin_check = false
For me, production was working correctly but staging and development were not and this fixed it for me.
As it turns out, Devise documentation is quite revealing with regard to this error:
For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.
The fix was to change code in my application controller from this:
protect_from_forgery with: :exception
To this:
protect_from_forgery prepend: true
This issue did not manifest itself until I attempted adding Audited or Paper Trail gems.
This happened to me on my development machine. Turns out I was setting
Rails.application.config.session_store
for security purpose in production. And somehow in this code gets run on development mode. And I have to comment out this line and it works fine now.
Rails.application.config.session_store :cookie_store, key: '_my_session', secure: true, same_site: :strict
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With