[ruby-on-rails] ActionController::InvalidAuthenticityToken

Below is an error, caused by a form in my Rails application:

Processing UsersController#update (for **ip** at 2010-07-29 10:52:27) [PUT]
  Parameters: {"commit"=>"Update", "action"=>"update", "_method"=>"put", "authenticity_token"=>"ysiDvO5s7qhJQrnlSR2+f8jF1gxdB7T9I2ydxpRlSSk=", **more parameters**}

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

This happens for every non-get request and, as you see, authenticity_token is there.

This question is related to ruby-on-rails

The answer is


I had the same issue but with pages which were page cached. Pages got buffered with a stale authenticity token and all actions using the methods post/put/delete where recognized as forgery attempts. Error (422 Unprocessable Entity) was returned to the user.

The solution for Rails 3:
Add:

 skip_before_filter :verify_authenticity_token  

or as "sagivo" pointed out in Rails 4 add:

 skip_before_action :verify_authenticity_token

On pages which do caching.

As @toobulkeh commented this is not a vulnerability on :index, :show actions, but beware using this on :put, :post actions.

For example:

 caches_page :index, :show  
 skip_before_filter :verify_authenticity_token, :only => [:index, :show]

Reference: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Note added by barlop- Rails 4.2 deprecated skip_before_filter in favour of skip_before_action https://guides.rubyonrails.org/4_2_release_notes.html "The *_filter family of methods have been removed from the documentation. Their usage is discouraged in favor of the *_action family of methods"

For Rails 6 (as "collimarco" pointed out) you can use skip_forgery_protection and that it is safe to use it for a REST API that doesn't use session data.


I had the same issue on localhost. I have changed the domain for the app, but in URLs and hosts file there was still the old domain. Updated my browser bookmarks and hosts file to use new domain and now everything works fine.


This happened to me when carrying out manual tests of the sign up process of my application (signing up/in with multiple users).

A very simple and pragmatic solution may be to do what I did, and use a different browser (or incognito if using chrome).

This was a much better solution in my case than disabling security features!!


For Development environment, I tried many of these attempts to fix this issue, in Rails 6. None of them helped. So if none of these suggestions worked for you, try below.

The only solution I found was to add a txt file into your /tmp folder.

In your app's root directory, either run:

touch tmp/caching-dev.txt

Or manually create a file by that name in your /tmp folder. Since this fixed it for me, I assume the root of the issue is a caching conflict.


There are several causes for this error, (relating to Rails 4).

1. Check <%= csrf_meta_tags %> present in page layout

2. check authenticity token is being sent with AJAX calls if using form_for helper with remote: true option.If not you can include the line <%= hidden_field_tag :authenticity_token, form_authenticity_token %> withing the form block.

3. If request is being sent from cached page, use fragment caching to exclude part of page that sends request e.g. button_to etc. otherwise token will be stale/invalid.

I would be reluctant to nullify csrf protection...


We had the same problem, but noticed that it was only for requests using http:// and not with https://. The cause was secure: true for session_store:

Rails.application.config.session_store(
  :cookie_store,
  key: '_foo_session',
  domain: '.example.com',
  secure: true
)

Fixed by using HTTPS ~everywhere :)


I had this issue with javascript calls. I fixed that with just requiring jquery_ujs into application.js file.


too late to answer but I found the solution.

When you define you own html form then you miss authentication token string that should be sent to controller for security reasons. But when you use rails form helper to generate a form you get something like following

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;">
    <input name="authenticity_token" type="hidden" 
      value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
    .
    .
    .
  </div>
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then removing , downgrading or upgrading rails.


This answer is much more specific to Ruby on Rails, but hopefully it will help someone.

You need to include the CSRF token with every non-GET request. If you're used to using JQuery, Rails has a helper library called jquery-ujs that builds on top of it and adds some hidden functionality. One of the things it does is automatically includes the CSRF token in every ajax request. See here.

If you switch away from it like I did you might find yourself with an error. You can just submit the token manually or use another library to help scrape the token from the DOM. See this post for more detail.


For me the cause of this issue under Rails 4 was a missing,

<%= csrf_meta_tags %>

Line in my main application layout. I had accidently deleted it when I rewrote my layout.

If this isn't in the main layout you will need it in any page that you want a CSRF token on.


ActionController::InvalidAuthenticityToken can also be caused by a misconfigured reverse proxy. This is the case if in the stack trace, you get a line looking like Request origin does not match request base_url.

When using a reverse proxy (such as nginx) as receiver for HTTPS request and transmitting the request unencrypted to the backend (such as the Rails app), the backend (more specifically: Rack) expects some headers with more information about the original client request in order to be able to apply various processing tasks and security measures.

More details are available here: https://github.com/rails/rails/issues/22965.

TL;DR: the solution is to add some headers:

upstream myapp {
  server              unix:///path/to/puma.sock;
}

location / {
  proxy_pass        http://myapp;
  proxy_set_header  Host $host;
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header  X-Forwarded-Proto $scheme;
  proxy_set_header  X-Forwarded-Ssl on; # Optional
  proxy_set_header  X-Forwarded-Port $server_port;
  proxy_set_header  X-Forwarded-Host $host;
}

I had this problem and the reason was because I copied and pasted a controller into my app. I needed to change ApplicationController to ApplicationController::Base


The authenticity token is a random value generated in your view to prove a request is submitted from a form on your site, not somewhere else. This protects against CSRF attacks:

http://en.wikipedia.org/wiki/Cross-site_request_forgery

Check to see who that client/IP is, it looks like they are using your site without loading your views.

If you need to debug further, this question is a good place to start: Understanding the Rails Authenticity Token

Edited to explain: It means they are calling the action to process your form submit without ever rendering your form on your website. This could be malicious (say posting spam comments) or it could indicate a customer trying to use your web service API directly. You're the only one who can answer that by the nature of your product and analyzing your requests.


Following Chrome Lighthouse recommendations for a faster application load, I have asynced my Javascript:

views/layout/application.html.erb

<%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload', async: true %>

This broke everything and got that Token error for my remote forms. Removing async: true fixed the problem.


I have checked the <%= csrf_meta_tags %> are present and clearing cookies in browser worked for me.


For rails 5, it better to add protect_from_forgery prepend: true than to skip the verify_authentication_token


Installing

gem 'remotipart' 

can help


If you have done a rake rails:update or otherwise recently changed your config/initializers/session_store.rb, this may be a symptom of old cookies in the browser. Hopefully this is done in dev/test (it was for me), and you can just clear all browser cookies related to the domain in question.

If this is in production, and you changed key, consider changing it back to use the old cookies (<- just speculation).


This happened to me when upgrading from Rails 4.0 to 4.2.

The 4.2 implementation of verified_request? looks at request.headers['X-CSRF-Token'], whereas the header my 4.0 app had been getting was X-XSRF-TOKEN. A quick fix in my ApplicationController was to add the function:

  def verify_authenticity_token
    request.headers['X-CSRF-Token'] ||= request.headers['X-XSRF-TOKEN']
    super
  end

Just adding the authenticity_token in form fixed it for me.

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

In rails 5, we need to add 2 lines of code

    skip_before_action :verify_authenticity_token
    protect_from_forgery prepend: true, with: :exception

Add

//= require rails-ujs 

in

\app\assets\javascripts\application.js

Maybe you have your NGINX setup for HTTPS but your certificates are invalid? I've had a similar problem in the past and redirecting from http to https solved the problem


Running rails dev:cache in my console fixed this for me! (Rails 6)

I think it might be something to do with Turbolinks, but CSRF only seems to work when local caching is enabled.