Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
73 lines (40 sloc) 2.68 KB

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, jQuery and ExtJS (let me know if you would like to see it working with some other library)


Install the plugin

$ script/plugin install git://

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

$ script/generate remote_forgery_protection


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

<script type="text/javascript"> 
  window._token = 'somecomplextoken';
<script src="/javascripts/remote_forgery_protection.js" type="text/javascript"></script>

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 ..

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

<%= remote_forgery_protection :inline => true %>

Useful Links

Blog post -

Rails documentation -

Inspired by -

You know about XSS. How about XSRF/CSRF? -

CSRF on Wikipedia -


Copyright © 2009 Vlado Cingel, released under the MIT license