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:

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s