Protect your XHR actions (RoR)

By | December 5, 2007

Using XHR within Ruby on Rails is as easy as adding up 1 and 1. We use e.g. the link_to_remote helper and point it to a controllers action. The small problem here is that the XHR actions are all available publicly. So calling the action directly within the browser works as well. I say ‘small’ problem because we cannot really prevent calling them directly but we can narrow the access only to XHR calls. We want to achieve that a common request to an XHR will fail. XHR actions will only be available if the request itself is an xhr?.

The solution with a bit of Rubyism: every xhr action needs to be postfixed with _xhr. If a calling request is not an xhr then we redirect the user the home url. For this we add a simple before_filter within our ApplicationController which will check all out actions. Here is the snippet…

  1. class ApplicationController < ActionController::Base
  2.   before_filter :protect_xhr_actions
  3.  
  4.   protected
  5.  
  6.   #protects all actions which ends with '_xhr' against a direct call (no xhr)
  7.   def protect_xhr_actions
  8.     redirect_to home_url and false if self.action_name.ends_with?('_xhr') and !request.xhr?
  9.   end
  10. end
  11. &#91;/ruby&#93;
  12.  
  13. Note: to use the <code>home_url</code> put something like the following into your <code>routes.rb</code>.
  14.  
  15. [ruby]
  16. #this gives us a home_url
  17. map.home '/', :controller => 'home'

You can also replace home_url by a hash pointing to specific controller and action. e.g. redirect_to {:controller => 'mycontroller', :action => 'myaction'} ...

Leave a Reply

*

* Copy This Password *

* Type Or Paste Password Here *

147,888 Spam Comments Blocked so far by Spam Free Wordpress