Rails 中的 protected_from_forgery 和 verify_authenticity_token 有什么区别?

Mys*_*ood 1 ruby-on-rails ruby-on-rails-5

我通常skip_before_action :verify_authenticity_token在 API 控制器中编写,但我刚刚发现还有一个protect_from_forgery except :action. 有什么区别以及我什么时候应该使用哪一个?

Sch*_*ern 6

查看 的代码,它是和protect_from_forgery的包装器。verify_authenticity_tokenverify_same_origin_request

def protect_from_forgery(options = {})
  options = options.reverse_merge(prepend: false)

  self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
  self.request_forgery_protection_token ||= :authenticity_token
  before_action :verify_authenticity_token, options
  append_after_action :verify_same_origin_request
end
Run Code Online (Sandbox Code Playgroud)

我读到的文档是,protect_from_forgery默认情况下,您可以为 ApplicationController 中的所有控制器打开 CSRF。用于skip_before_action :verify_authenticity_token在子类中有选择地关闭它。