Wolfmans Howlings

A programmers Blog about Programming solutions and a few other issues

Turn off forgery protection when using caching

Posted by Jim Morris on Sat Dec 18 01:04:06 -0800 2010

This one does not seem to be documented, and I just got bit.

After porting my blog engine to Rails 3, I noticed that after a while comments were being rejected with an ActionController::InvalidAuthenticityToken error.

It turns out this is due to the token being cached, as I use fragment caching. It is a pity they do not document that you must turn it off if you use caching, but I guess it is obvious once you know about it.

Turn it off using:-

config.action_controller.allow_forgery_protection = false in config/application.rb

I'm going to be changing the way I allow people to submit comments as the amount of attempts to post spam is amazing. The simple captcha I use works, but I figured if I generate the form dynamically using Javascript when they click the leave comment link, then the spambots won't be able to find the fields to fill in, so they will fail before they ever get to try to post. We'll see if that works :) Then I may be able to turn on forgery protection again as the comment form won't be cached.

I guess you could also make sure the comment form is a fragment and explicitly don't cache it.

Posted in Rails  |  Tags rails,authenticity  |  4 comments

Comments

  1. Bruno Michel said on Sat Dec 18 07:29:46 -0800 2010
    The protection against CSRF is generally a good thing to have. If you're using caching and have problems with only posting comments, you can disable this check only for this specific controller:

    class CommentsController
      skip_before_filter :verify_authenticity_token
      # [...]
    end
  2. threadhead@gmail.com said on Sat Dec 18 11:37:12 -0800 2010
    Adding 'skip_before_filer :veriify_authenticity_token' is also helpful if you are using controllers for both html (via users) and JS/XML (via an api).
  3. wolfman said on Sat Dec 18 15:33:51 -0800 2010
    Seeing as the only form posted in this application is for comments, then turning it off globally is an option.

    I agree for a more complex app that selectively turning it off would be more appropriate.
  4. Even so said on Sun Sep 02 22:19:38 -0700 2012
    Regardless if it's a simple app. It might grow, doing things right from the start is the right way.

(leave email »)