protect_from_forgery with: :exception是如何工作的?
我想要编辑代码来查看它并从中学习。但是,我找不到它在更高抽象级别中的位置。
发布于 2013-10-23 01:55:18
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中定义的异常。
https://stackoverflow.com/questions/19524728
复制相似问题