ActionController::InvalidAuthenticityToken - Understanding this Error in Rails
I’ve seen a lot of help requests about a specific controller error that many people encounter in Rails after sending a post request from a form they’ve custom built. The ActionController::InvalidAuthenticityToken error is Rails basically telling you that it’s not going to fall victim to a cross-site request forgery (CSRF) attack. Here’s a simplified explanation of why this occurs and how to fix the error to keep your application secure and fix the problem.
The ActionController::InvalidAuthenticityToken error typically occurs when some one uncomments the :secret key in your application.rb file for the protect_from_forgery option.
For example:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery :secret => 'randomstringoflettersandnumbershere'
We typically do this when using the database for sessions instead of the filesystem. The error itself is caused by the controller not receiving a match to the key specified above in application.rb.
In other words, your forms aren’t sending the key to the application, so it thinks you’re trying to perform a CSRF. The way to fix this is to simply supply the key. However, hard-coding it into each and every form can be a pain. That’s why you need to use Rails’ form helpers.
Instead of doing a form like this:
<form action="blah" method="post">
First Name: <input type="text" name="first_name">
...
You need to do it using Rails’ view helpers.
<%= form_tag :action => "signup" %>
<%= text_field "user", "first_name", :size => 20 %>
...
This will have Rails automatically generate the secret key for you in every form, thus alleviating the problem and helping to protect you from a CSRF attack simultaneously
The documentation lists a few more details of course. As always, don’t assume this is all you have to do to secure your application - there are plenty of other measures you should take depending on the scope, access availability, and other requirements of your application.
Trackbacks
Use the following link to trackback from your own site:
http://blog.jaustinhughey.com/trackbacks?article_id=actioncontroller-invalidauthenticitytoken-understanding-this-error-in-rails&day=02&month=04&year=2008