Rails CSRF保护:编写before_filter是否正确?

时间:2011-11-05 11:00:58

标签: ruby-on-rails-3.1 csrf-protection protect-from-forgery

我的应用程序控制器如下所示:

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

如果没有check_csrf,Rails会在错误的响应中向服务器控制台写入警告,然后通常会继续执行。所以我不得不写自己的check_csrf。现在它工作正常。这是对的吗?是否有一种简单的方法可以停止执行错误的请求?

Rails版本:3.1。

1 个答案:

答案 0 :(得分:2)

我认为你应该覆盖handle_unverified_request

类似的东西:

class ApplicationController < ActionController::Base
  protect_from_forgery

  protected
    def handle_unverified_request
      redirect_to root_url, :error => "forgery protection"
    end
end