Rails, CSRF and Ajax requests
Rails protects controller actions from CSRF (Cross-Site Request Forgery) attacks with a token based on a random string stored in the session. The token parameter is named authenticity_token by default and will be embedded in all forms and Ajax requests generated by Rails.
You should also add this token to all Ajax request that you hand coded. As suggested in Rails documentation you can add this line in head section.
and then add authenticity_token to parameters option of Ajax requests
Remote forgery protection plugin
This can get tedious if you have a lot of Ajax requests so I wrote a simple plugin that adds authenticity token to all Ajax requests automatically.
You can install it with
Now all you have to do is add this line inside head section of you’re layout
and all non GET Ajax request will have authenticity_token parameter automatically included.
Magic is done by wrapping Ajax.Base using Function#wrap method so this will work only if you are using Prototype. I plan to add support for other libraries (if there is interest) in the future so keep in touch.
Remote forgery protection currently supports Prototype, jQuery and ExtJS. Let me know if you would like to see it working with some other library
Plugin page: http://github.com/vlado/remote_forgery_protection
More info:
api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html isc.sans.org/diary.html?storyid=1750 en.wikipedia.org/wiki/Cross-site_request_forgery opensoul.org/2008/10/24/ajax-and-request-forgery-protection