Rails 5 Actioncontroller::Invalidauthenticitytoken Error

Rails 5 ActionController::InvalidAuthenticityToken error

Note: While this answer has the desired effect, it does so by reducing overall security. The below answer by Alon is more correct and maintains the security of the site.

class BugsController < ApplicationController
skip_before_filter :verify_authenticity_token
protect_from_forgery prepend: true, with: :exception
before_action :authenticate_user!
before_action :set_bug, only: [:show, :edit, :update]
end

Like This

Intermittent Rails 5 ActionController::InvalidAuthenticityToken

Thanks to the rubber duck, I have reproduced the issue.

  1. Sign out
  2. Go "back" to the cached app UI.
  3. Click the button to generate a POST request.
  4. Observe the exception.

The solution here is to use rescue_from to likely redirect the user to the sign in page.

Thank you rubber duckie!

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

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.

Rails 5 ActionController::InvalidAuthenticityToken on Production Enviroment Nginx

My problem was that in my nginx config I was setting header Host two times and this was causing url generation misleadings, which in turn was invalidating form submissions.

  proxy_pass http://localhost:4000;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
**proxy_set_header Host $http_host;**
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
**proxy_set_header Host $http_host;**
proxy_set_header X-Real-Port $server_port;
proxy_set_header X-Real-Scheme $scheme;
proxy_set_header X-NginX-Proxy true;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Ssl on;

Just removing one the two proxy_set_header Host $http_host; did the trick

ActionController::InvalidAuthenticityToken in Rails 5

Try disabling Turbolinks. What version of Rails are you running?

For help disabling turbolinks, refer here: How to disable turbolinks in Rails 5?



Related Topics



Leave a reply



Submit