56yards

A Web Developers perspective on the the latest web tech, ruby on rails, asp.net and anything of interest from South Wales, UK.

Projects

ecommerce observer

Weird Rails errors cropping up with CanCan and Devise

Well this morning I decided to update my rails app ($ bundle update rails) and long and behold something has broken my app. More specifically AJAX requests have stopped working.

My app uses the CanCan gem, which is used for authorisation and one of the errors where “load_and_authorize_resource would come back with unauthorised access” eventhough the user had the correct access.

Another error, that cropped up was with the Devise gem which is used for authentication. Error saying “current_user is nil” from line  @user = User.find(current_user) even though I had logged in and the current_user was set.

Anyway, after many frustrations and head bashing the finger started to point to a recent update to rails that prevents CSRF bypassing. You can read all about it here http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails

The fix, as I use jQuery in my app (instead of the default Prototype, which is about to change, long overdue may I add) is to add a CSRF token header tag to every AJAX request that gets called inside your app.

The most convenient way that I have found to do this is to add the following inside your <head> tag in application.html.erb. This way, the tag will automatically be applied to all AJAX requests so you will not need to manually add it yourself.

<script type=”text/javascript”>

$(function() {

       /*
         * Registers a callback which copies the csrf token into the
         * X-CSRF-Token header with each ajax request. Necessary to
         * work with rails applications which have fixed
         * CVE-2011-0447
        */
        $.ajaxSetup({
          headers: {
            “X-CSRF-Token”: $(“meta[name=’csrf-token’]”).attr(‘content’)
          }
        });

});

</script>

Again, if your using Prototype or some other JavaScript library then please check out http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails as I’m sure here you will find the alternative fixes for your library.

  1. 56yards posted this