ActionController::InvalidAuthenticityToken Rails 5 / Devise / Audited / PaperTrail gem

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:

  • rails 5.0.2
  • devise => 4.2.1
  • paper_trail => 7.0.1

Steps to Reproduce:

  1. Create Rails 5 application
  2. Add Devise gem
  3. Add Audited or Paper Trail gem
  4. Attempt to login

Answers


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.


In my project we have that problem and we can't to override protect_from_forgery. The solution founded is indicate the github of audited and worked for me.

Put this in gemfile:

gem "audited", github: "collectiveidea/audited"

As mentioned in the documentation.

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.

I have used something like this and it works for me.

class WelcomeController < ::Base
    protect_from_forgery with: :exception
    before_action :authenticate_model!
end

The solution for me was to manually go to my browser's settings and delete the cache.


Need Your Help