首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >protect_from_forgery with::exception在哪里?

protect_from_forgery with::exception在哪里?
EN

Stack Overflow用户
提问于 2013-10-23 01:40:44
回答 1查看 13K关注 0票数 18

protect_from_forgery with: :exception是如何工作的?

我想要编辑代码来查看它并从中学习。但是,我找不到它在更高抽象级别中的位置。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-23 01:55:18

你可以在Github上找到它:https://github.com/rails/rails/blob/c60be72c5243c21303b067c9c5cc398111cf48c8/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L88

代码语言:javascript
复制
def protect_from_forgery(options = {})
  self.forgery_protection_strategy = protection_method_class(options[:with] || :null_session)
  self.request_forgery_protection_token ||= :authenticity_token
  prepend_before_action :verify_authenticity_token, options
end

with: :exception传递给protection_method_class(:exception)。这样做的话:

代码语言:javascript
复制
def protection_method_class(name)
  ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
  rescue NameError
  raise ArgumentError, 'Invalid request forgery protection method, use :null_session, :exception, or :reset_session'
end

然后是这个ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)。这里的name.to_s.classify将是Exception

然后你可以找到:

代码语言:javascript
复制
module ProtectionMethods
  class Exception
    def initialize(controller)
      @controller = controller
    end

    def handle_unverified_request
      raise ActionController::InvalidAuthenticityToken
    end
  end
end

然后设置一个before_action:verify_authenticity_token

代码语言:javascript
复制
def verify_authenticity_token
  unless verified_request?
    logger.warn "Can't verify CSRF token authenticity" if logger
    handle_unverified_request
  end
end

它使用前面定义的策略:

代码语言:javascript
复制
def handle_unverified_request
  forgery_protection_strategy.new(self).handle_unverified_request
end

引发在Exception中定义的异常。

票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19524728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档