2013-10-22 33 views

回答

10

你可以在這裏找到它在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定義。

+1

你能解釋一下嗎? –

+5

這個解釋看起來非常簡單直接。 – zeantsoi

+3

基本上,如果沒有足夠的保護,或者如果存在CSFR類型的請求,則會引發「例外」。 「例外」是造成故障開始的原因。這迫使Rails告訴你什麼導致了異常。 – Matteo