【问题标题】:protect_from_forgery with: :exception where?Protect_from_forgery with: :exception 在哪里?
【发布时间】:2025-12-24 02:20:08
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

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

    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)。哪个:

    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

    然后你可以找到:

    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

    def verify_authenticity_token
      unless verified_request?
        logger.warn "Can't verify CSRF token authenticity" if logger
        handle_unverified_request
      end
    end
    

    使用之前定义的策略:

    def handle_unverified_request
      forgery_protection_strategy.new(self).handle_unverified_request
    end
    

    引发Exception 中定义的异常。

    【讨论】:

    • 你能用更简单的术语解释一下吗?
    • 这个解释看起来非常简单明了。
    • 基本上,如果没有足够的保护,或者有 CSFR 类型的请求,它会引发“异常”。 “异常”是导致故障开始的原因。这会强制 Rails 告诉你是什么导致了异常。
    • @thegauraw ...除了“这篇文章”不再存在。
    • 我猜这篇文章的意思是:Understanding Rails' protect_from_forgery