Skip to content

Rails plugin that automatically adds authenticity token to Ajax request

License

Notifications You must be signed in to change notification settings

vlado/remote_forgery_protection

Repository files navigation

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)

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

<script type="text/javascript"> 
  window._token = 'somecomplextoken';
</script> 
<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 ..
</script>

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

<%= remote_forgery_protection :inline => true %>

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

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

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

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

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

Licence

Copyright © 2009 Vlado Cingel, released under the MIT license

About

Rails plugin that automatically adds authenticity token to Ajax request

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages