| Module | ActionController::RequestForgeryProtection |
| In: |
actionpack/lib/action_controller/request_forgery_protection.rb
|
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 6 def self.included(base) base.class_eval do class_inheritable_accessor :request_forgery_protection_options self.request_forgery_protection_options = {} helper_method :form_authenticity_token helper_method :protect_against_forgery? end base.extend(ClassMethods) end
No secret was given, so assume this is a cookie session store.
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 117 def authenticity_token_from_cookie_session session[:csrf_id] ||= CGI::Session.generate_unique_id session.dbman.generate_digest(session[:csrf_id]) end
Generates a unique digest using the session_id and the CSRF secret.
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 106 def authenticity_token_from_session_id key = if request_forgery_protection_options[:secret].respond_to?(:call) request_forgery_protection_options[:secret].call(@session) else request_forgery_protection_options[:secret] end digest = request_forgery_protection_options[:digest] ||= 'SHA1' OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new(digest), key.to_s, session.session_id.to_s) end
Sets the token value for the current session. Pass a :secret option in protect_from_forgery to add a custom salt to the hash.
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 93 def form_authenticity_token @form_authenticity_token ||= if request_forgery_protection_options[:secret] authenticity_token_from_session_id elsif session.respond_to?(:dbman) && session.dbman.respond_to?(:generate_digest) authenticity_token_from_cookie_session elsif session.nil? raise InvalidAuthenticityToken, "Request Forgery Protection requires a valid session. Use #allow_forgery_protection to disable it, or use a valid session." else raise InvalidAuthenticityToken, "No :secret given to the #protect_from_forgery call. Set that or use a session store capable of generating its own keys (Cookie Session Store)." end end
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 122 def protect_against_forgery? allow_forgery_protection && request_forgery_protection_token end
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 88 def verifiable_request_format? request.format.html? || request.format.js? end
Returns true or false if a request is verified. Checks:
# File actionpack/lib/action_controller/request_forgery_protection.rb, line 81 def verified_request? !protect_against_forgery? || request.method == :get || !verifiable_request_format? || form_authenticity_token == params[request_forgery_protection_token] end