Search code examples
ruby-on-rails-3.1csrf-protectionprotect-from-forgery

Rails CSFR protection: is it corrent to write before_filter?


My application controller looks like this:

class ApplicationController < ActionController::Base
  protect_from_forgery
  before_filter :check_csrf
  def check_csrf
    if not verified_request?
      redirect_to root_url, :error => "forgery protection"
      return
    end
  end
end

Without check_csrf, Rails writes warning to server console on bad responses, then execution continues as usually. So I had to write my own check_csrf. Now it works fine. Is it correct? Is there a simplier way to stop execution of bad request?

Rails version: 3.1.


Solution

  • I think you should override handle_unverified_request.

    Something like that:

    class ApplicationController < ActionController::Base
      protect_from_forgery
    
      protected
        def handle_unverified_request
          redirect_to root_url, :error => "forgery protection"
        end
    end