remote_forgery_protection icon indicating copy to clipboard operation
remote_forgery_protection copied to clipboard

Rails plugin that automatically adds authenticity token to Ajax request

= Remote Forgery Protection

Remote Forgery Protection is a Rails plugin that automatically adds authenticity token to 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.

What about hand coded Ajax request? You can manually add authenticity_token parameter to all Ajax requests or you can let Remote Forgery Protection plugin do everything for you.

Supported Javascript libraries: {Prototype}[http://www.prototypejs.org], {jQuery}[http://www.jquery.com] and {ExtJS}[http://www.extjs.com] (let me know if you would like to see it working with some other library)

== Installation

Install the plugin

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

(Optional but recommended) Generate remote_forgery_protection.js file by running

$ script/generate remote_forgery_protection

== Usage

Just add this line in your head section

<%= remote_forgery_protection %>

and all future non GET Ajax request will automatically send authenticity_token parameter. You will also have global variable _token to use anywhere in you're scripts.

== How it works

This will produce something like

If file /javascripts/remote_forgery_protection.js doesn't exist, all the code will be included inline and output will now look like

<script type="text/javascript"> 
  window._token = 'somecomplextoken';
  Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(function() {
    var args = $A(arguments), proceed = args.shift();
    ... some javascript code ...
    proceed.apply(null, args);
  });
  ... some javascript code ..
</script>

You can also force javascript to be included inline by passing :inline => true option

<%= remote_forgery_protection :inline => true %>

== Useful Links

Blog post - http://kolodvor.net/2010/01/02/rails-csrf-and-ajax-requests

Rails documentation - http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Inspired by - http://opensoul.org/2008/10/24/ajax-and-request-forgery-protection

You know about XSS. How about XSRF/CSRF? - http://isc.sans.org/diary.html?storyid=1750

CSRF on Wikipedia - http://en.wikipedia.org/wiki/Cross-site_request_forgery

== Licence

Copyright (c) 2009 Vlado Cingel, released under the MIT license