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.

  <%= javascript_tag "window._token = '#{form_authenticity_token}'" %>;

and then add authenticity_token to parameters option of Ajax requests

  new Ajax.Request('/some/url', {
    parameters: "foo=bar&authenticity_token="+_token
  });

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

  script/plugin install git://github.com/vlado/remote_forgery_protection.git

Now all you have to do is add this line inside head section of you’re layout

  <%= remote_forgery_protection %>

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

2 thoughts on “Rails, CSRF and Ajax requests

  1. Great – many thanks!

    Although using Prototype I did have to tweak the line:

    var encodedToken = encodeURIComponent(_token);

    as my app is just using the token without encoding it. I’m using Rails 2.3.11.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>