How does protect_from_forgery with: :exception
work?
I'd like to edit the code to look at it and learn from it. However, I cannot find where it is placed as in a higher level of abstraction.
You can find it here on 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
The with: :exception
is passed to protection_method_class(:exception)
. Which does :
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
Then this ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
. name.to_s.classify
here will be Exception
.
Then you can find:
module ProtectionMethods
class Exception
def initialize(controller)
@controller = controller
end
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end
All of this sets the way the invalid authenticity will be handled.
Then it sets a 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
Which uses the previously defined strategy:
def handle_unverified_request
forgery_protection_strategy.new(self).handle_unverified_request
end
To raise the exception as defined in Exception
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With