Làm thế nào để protect_from_forgery with: :exception
hoạt động?
Tôi muốn chỉnh sửa mã để xem nó và học hỏi từ nó. Tuy nhiên, tôi không thể tìm thấy nó được đặt ở đâu vì ở mức độ trừu tượng cao hơn.
Làm thế nào để protect_from_forgery with: :exception
hoạt động?
Tôi muốn chỉnh sửa mã để xem nó và học hỏi từ nó. Tuy nhiên, tôi không thể tìm thấy nó được đặt ở đâu vì ở mức độ trừu tượng cao hơn.
Bạn có thể tìm thấy nó ở đây trên 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
Các with: :exception
sẽ được chuyển cho protection_method_class(:exception)
. Cái nào:
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
Sau đó, điều này ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify)
. name.to_s.classify
đây sẽ là Exception
.
Sau đó, bạn có thể tìm thấy:
module ProtectionMethods
class Exception
def initialize(controller)
@controller = controller
end
def handle_unverified_request
raise ActionController::InvalidAuthenticityToken
end
end
end
Tất cả những điều này đặt ra cách xử lý tính xác thực không hợp lệ. Sau đó, nó đặt một 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
Sử dụng chiến lược đã xác định trước đó:
def handle_unverified_request
forgery_protection_strategy.new(self).handle_unverified_request
end
Để nâng cao ngoại lệ như được định nghĩa trong Exception
.