Skip Rails AuthenticityToken Check, Sometimes

Earlier today, Elad Meidar asked on Twitter about how to bypass checking the Authenticity Token in Rails for an action, sometimes. The example he mentioned was for a write API but this could theoretically be used for other situations where you only want to skip the authenticity token check of an action under specific circumstances. We went back and fort

First off, you need to do some before filter work:

skip_before_filter :verify_authenticity_token, :only => [:your_action]
before_filter :semi_verify_authenticity_token, :only => [:your_action]

Then you need a function to define when to check for the token authenticity:

def semi_verify_authenticity_token
  verify_authenticity_token unless request.xhr? # Or whatever other criteria you would use

All you really have to do then is make sure that verify_authenticity_token gets called based on the params or request and you should be set. This can be useful for APIs or AJAX calls calls to a given action where you don’t mind skipping the token check, but you still want to enforce it for the regular HTML browser view.

Posted in Uncategorized at April 7th, 2010. Trackback URI: trackback
Tags: , , , , , ,

No Responses to “Skip Rails AuthenticityToken Check, Sometimes”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>