protect_from_forgery with: :exception
如何工作?protect_from_forgery与::异常在哪里?
我想编辑代码以查看它并从中学习。但是,我无法找到它的位置,因为它处于更高层次的抽象中。
protect_from_forgery with: :exception
如何工作?protect_from_forgery与::异常在哪里?
我想编辑代码以查看它并从中学习。但是,我无法找到它的位置,因为它处于更高层次的抽象中。
你可以在这里找到它在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
定义。
你能解释一下吗? –
这个解释看起来非常简单直接。 – zeantsoi
基本上,如果没有足够的保护,或者如果存在CSFR类型的请求,则会引发“例外”。 “例外”是造成故障开始的原因。这迫使Rails告诉你什么导致了异常。 – Matteo