Always getting an invalid authenticity token error
Sat May 02 21:59:19 -0700 2009
I had a Ruby on Rails app giving a bunch of invalid authenticity token errors. I spent a while hunting down the solution until I found this write up. Very useful.
This write up was by Peter De Berdt on one of the Ruby mailing lists, I am putting it here more for my own future (maybe) reference as it is a very good solution for the situation I was running into. The entire thread is at the ruby forum site
If you have a situation where you are getting invalid authenticity tokens and are doing strange things with forms on your website with file uploads etc, and can’t for some reason just use the authenticity form helper, then this solution worked for me and should work for you too.
The solution is pretty simple to be honest:
In your view layout file, add this to the
1 2 3 |
<script type="text/javascript" charset="utf-8"> window._token = '<%= form_authenticity_token -%>'; </script> |
In application.js, add the following:
1 2 3 4 5 6 7 |
Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap( function(p, options){ p(options); this.options.parameters = this.options.parameters || {}; this.options.parameters.authenticity_token = window._token || ''; } ); |
It will automatically add the authenticity token to ALL ajax requests, even those you invoke from custom code (graceful degrading and/or even delegated events for example).
A similar solution for those swapping out Prototype with JQuery has been posted here
As for file uploaders, a normal field within a form (multipart=true) will be sent as part of the form (and isn’t an ajax request in the first place) and shouldn’t be a problem. If you are using ANY other “ajax” uploader, there’s more to it. I already posted several times on how to get SWFUpload to play nicely with Rails, an overview with links to the appropriate posts can be found here.



Sun May 03 13:35:27 -0700 2009
This technique helped me with all my manually created ajax calls, but it seems to have broken the authenticity token sent with the rails helpers like link_to_remote…. I get the following error:
Processing Store::CartItemsController#create (for 127.0.0.1 at 2009-05-04 12:27:54) [POST] Parameters: {“product_id”=>”758”, “authenticity_token”=>””, ”_”=>”“} ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
Apparently token is parsed to nil?
Sun May 03 13:32:52 -0700 2009
To clarify my post above, it seems like the code snippet has trouble with the ajax calls generated by the rails helpers like link_to_remote, and the ajax request is never sent…