2013-10-22 6 views
14

protect_from_forgery with: :exceptionはどのように機能しますか?protect_from_forgery with::exceptどこに?

私はそれを見てそれから学ぶためにコードを編集したいと思います。しかし、抽象度が高いほど、どこに配置されているのかわかりません。

答えて

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: :exceptionprotection_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.classifyExceptionとなります。

次に、あなたが見つけることができます:

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 

Exceptionで定義されているよう

def handle_unverified_request 
    forgery_protection_strategy.new(self).handle_unverified_request 
end 

は例外を発生させます。

+1

あなたはこれをより簡単に説明できますか? –

+5

この説明は、できるだけ単純でわかりやすいようです。 – zeantsoi

+3

基本的には、十分な保護がない場合、またはCSFRタイプの要求がある場合は、「例外」が発生します。 「例外」とは、障害の原因となったものです。これにより、Railsは例外の原因を教えてくれます。 – Matteo

関連する問題