123456789_123456789_123456789_123456789_123456789_

Module: ActionController::RequestForgeryProtection

Overview

Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks by checking the Sec-Fetch-Site header sent by modern browsers to indicate the relationship between request’s initiator origin and the origin of the requested resource (developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)

For applications that need to support older browsers, there’s a token-based fallback. A token is included in the rendered HTML for your application. This token is stored as a random string in the session, to which an attacker does not have access. When a request reaches your application, ::Rails verifies the received token with the token in the session. All requests are checked except GET requests as these should be idempotent. Keep in mind that all session-oriented requests are CSRF protected by default, including JavaScript and HTML requests.

Since HTML and JavaScript requests are typically made from the browser, we need to ensure to verify request authenticity for the web browser. We can use session-oriented authentication for these types of requests, by using the protect_from_forgery method in our controllers.

GET requests are not protected since they don’t have side effects like writing to the database and don’t leak sensitive information. JavaScript requests are an exception: a third-party site can use a <script> tag to reference a JavaScript URL on your site. When your JavaScript response loads on their site, it executes. With carefully crafted JavaScript on their end, sensitive data in your JavaScript response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or Ajax) requests are allowed to make requests for JavaScript responses.

Subclasses of Base are protected by default with the :exception strategy, which raises an InvalidCrossOriginRequest error on unverified requests.

APIs may want to disable this behavior since they are typically designed to be state-less: that is, the request API client handles the session instead of ::Rails. One way to achieve this is to use the :null_session strategy instead, which allows unverified requests to be handled, but with an empty session:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

Note that API only applications don’t include this module or a session middleware by default, and so don’t require CSRF protection to be configured.

The token parameter is named authenticity_token by default. The name and value of this token must be added to every layout that renders forms by including csrf_meta_tags in the HTML head.

Learn more about CSRF attacks and securing your application in the [Ruby on ::Rails Security Guide](guides.rubyonrails.org/security.html).

Constant Summary

::ActiveSupport::Callbacks - Included

CALLBACK_FILTER_TYPES

::AbstractController::Callbacks - Included

DEFAULT_INTERNAL_METHODS

::AbstractController::Callbacks - Attributes & Methods

::AbstractController::Helpers - Attributes & Methods

Class Method Summary

::ActiveSupport::DescendantsTracker - self

::ActiveSupport::Concern - Extended

class_methods

Define class methods from given block.

included

Evaluate given block in context of base class, so that you can write class macros here.

prepended

Evaluate given block in context of base class, so that you can write class macros here.

append_features, prepend_features

Instance Attribute Summary

::AbstractController::Callbacks - Included

Instance Method Summary

::AbstractController::Callbacks - Included

#process_action

Override AbstractController::Base#process_action to run the process_action callbacks around the normal behavior.

::ActiveSupport::Callbacks - Included

#run_callbacks

Runs the callbacks for the given event.

#halted_callback_hook

A hook invoked every time a before callback is halted.

::AbstractController::Helpers - Included

DSL Calls

included

[ GitHub ]


79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 79

included do
  # Sets the token parameter name for RequestForgery. Calling
  # `protect_from_forgery` sets it to `:authenticity_token` by default.
  singleton_class.delegate :request_forgery_protection_token, :request_forgery_protection_token=, to: :config
  delegate :request_forgery_protection_token, :request_forgery_protection_token=, to: :config
  self.request_forgery_protection_token ||= :authenticity_token

  # Holds the class which implements the request forgery protection.
  singleton_class.delegate :forgery_protection_strategy, :forgery_protection_strategy=, to: :config
  delegate :forgery_protection_strategy, :forgery_protection_strategy=, to: :config
  self.forgery_protection_strategy = nil

  # Controls whether request forgery protection is turned on or not. Turned off by
  # default only in test mode.
  singleton_class.delegate :allow_forgery_protection, :allow_forgery_protection=, to: :config
  delegate :allow_forgery_protection, :allow_forgery_protection=, to: :config
  self.allow_forgery_protection = true if allow_forgery_protection.nil?

  # Controls whether a CSRF failure logs a warning. On by default.
  singleton_class.delegate :log_warning_on_csrf_failure, :log_warning_on_csrf_failure=, to: :config
  delegate :log_warning_on_csrf_failure, :log_warning_on_csrf_failure=, to: :config
  self.log_warning_on_csrf_failure = true

  # Controls whether the Origin header is checked in addition to the CSRF token.
  singleton_class.delegate :forgery_protection_origin_check, :forgery_protection_origin_check=, to: :config
  delegate :forgery_protection_origin_check, :forgery_protection_origin_check=, to: :config
  self.forgery_protection_origin_check = false

  # Controls whether form-action/method specific CSRF tokens are used.
  singleton_class.delegate :per_form_csrf_tokens, :per_form_csrf_tokens=, to: :config
  delegate :per_form_csrf_tokens, :per_form_csrf_tokens=, to: :config
  self.per_form_csrf_tokens = false

  # The strategy to use for storing and retrieving CSRF tokens.
  singleton_class.delegate :csrf_token_storage_strategy, :csrf_token_storage_strategy=, to: :config
  delegate :csrf_token_storage_strategy, :csrf_token_storage_strategy=, to: :config
  self.csrf_token_storage_strategy = SessionStore.new

  # The strategy to use for verifying requests. Options are:
  # * :header_only - Use Sec-Fetch-Site header only (default, modern browsers)
  # * :header_or_legacy_token - Combined approach: Sec-Fetch-Site with fallback to token
  singleton_class.delegate :forgery_protection_verification_strategy, :forgery_protection_verification_strategy=, to: :config
  delegate :forgery_protection_verification_strategy, :forgery_protection_verification_strategy=, to: :config
  self.forgery_protection_verification_strategy = :header_or_legacy_token

  # Origins allowed for cross-site requests, such as OAuth/SSO callbacks,
  # third-party embeds, and legitimate remote form submission.
  # Example: %w[ https://accounts.google.com ]
  singleton_class.delegate :forgery_protection_trusted_origins, :forgery_protection_trusted_origins=, to: :config
  delegate :forgery_protection_trusted_origins, :forgery_protection_trusted_origins=, to: :config
  self.forgery_protection_trusted_origins = []

  # Controls the default strategy used when calling protect_from_forgery without arguments.
  # Defaults to :null_session for backwards compatibility, but will change to :exception
  # in a future version of Rails.
  singleton_class.delegate :default_protect_from_forgery_with, :default_protect_from_forgery_with=, to: :config
  delegate :default_protect_from_forgery_with, :default_protect_from_forgery_with=, to: :config
  self.default_protect_from_forgery_with = :null_session

  helper_method :form_authenticity_token
  helper_method :protect_against_forgery?
end

Class Attribute Details

._helper_methods (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 13

class_attribute :_helper_methods, default: Array.new

._helper_methods?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 13

class_attribute :_helper_methods, default: Array.new

.raise_on_missing_callback_actions (rw) Also known as: #raise_on_missing_callback_actions

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/callbacks.rb', line 38

mattr_accessor :raise_on_missing_callback_actions, default: false

Instance Attribute Details

#_helper_methods (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 13

class_attribute :_helper_methods, default: Array.new

#_helper_methods?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 13

class_attribute :_helper_methods, default: Array.new

#any_authenticity_token_valid?Boolean (readonly, private)

Checks if any of the authenticity tokens from the request are valid.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 698

def any_authenticity_token_valid? # :doc:
  request_authenticity_tokens.any? do |token|
    valid_authenticity_token?(session, token)
  end
end

#cross_origin_request?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 544

def cross_origin_request?
  !valid_request_origin? ||
    sec_fetch_site_value == "cross-site" ||
    using_header_only_for_forgery_protection?
end

#marked_for_same_origin_verification?Boolean (readonly, private)

If the #verify_request_for_forgery_protection before_action ran, verify that JavaScript responses are only served to same-origin GET requests.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 596

def marked_for_same_origin_verification? # :doc:
  @_marked_for_same_origin_verification ||= false
end

#non_xhr_javascript_response?Boolean (readonly, private)

Check for cross-origin JavaScript responses.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 601

def non_xhr_javascript_response? # :doc:
  %r(\A(?:text|application)/javascript).match?(media_type) && !request.xhr?
end

#origin_trusted?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 685

def origin_trusted?
  origin = request.origin
  origin.present? && forgery_protection_trusted_origins.include?(origin)
end

#protect_against_forgery?Boolean (readonly, private)

Checks if the controller allows forgery protection.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 841

def protect_against_forgery? # :doc:
  allow_forgery_protection && (!session.respond_to?(:enabled?) || session.enabled?)
end

#raise_on_missing_callback_actions (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/callbacks.rb', line 38

mattr_accessor :raise_on_missing_callback_actions, default: false

#using_header_only_for_forgery_protection?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 633

def using_header_only_for_forgery_protection?
  forgery_protection_verification_strategy == :header_only
end

#valid_request_origin?Boolean (readonly, private)

Checks if the request originated from the same origin by looking at the Origin header.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 857

def valid_request_origin? # :doc:
  if forgery_protection_origin_check
    # We accept blank origin headers because some user agents don't send it.
    raise InvalidCrossOriginRequest, NULL_ORIGIN_MESSAGE if request.origin == "null"
    request.origin.nil? || request.origin == request.base_url
  else
    true
  end
end

#verified_request?Boolean (readonly, private)

Returns true or false if a request is verified. The verification method depends on the configured forgery_protection_verification_strategy:

  • :header_only - Uses Sec-Fetch-Site header only (default)

  • :header_or_legacy_token - Uses Sec-Fetch-Site header with fallback to token

For all strategies, GET and HEAD requests are allowed without verification.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 620

def verified_request? # :doc:
  request.get? || request.head? || !protect_against_forgery? ||
    (valid_request_origin? && verified_request_for_forgery_protection?)
end

#verified_request_for_forgery_protection?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 625

def verified_request_for_forgery_protection?
  if using_header_only_for_forgery_protection?
    verified_via_header_only?
  else
    verified_with_legacy_token?
  end
end

#verified_via_header_only?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 637

def verified_via_header_only?
  case sec_fetch_site_value
  when "same-origin", "same-site"
    true
  when "cross-site"
    origin_trusted?
  when nil
    !request.ssl? && !ActionDispatch::Http::URL.secure_protocol
  else
    false
  end
end

#verified_with_legacy_token?Boolean (readonly, private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 650

def verified_with_legacy_token?
  case sec_fetch_site_value
  when "same-origin", "same-site"
    true
  when "cross-site"
    origin_trusted?
  else # "none" or missing
    instrument_csrf_token_fallback
    any_authenticity_token_valid?
  end
end

Instance Method Details

#append_sec_fetch_site_to_vary_header (private)

Appends Sec-Fetch-Site to the Vary header. This ensures proper cache behavior since the response may vary based on this header.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 581

def append_sec_fetch_site_to_vary_header # :doc:
  vary_header = response.headers["Vary"].to_s.split(",").map(&:strip).reject(&:blank?)
  unless vary_header.include?("Sec-Fetch-Site")
    response.headers["Vary"] = (vary_header + ["Sec-Fetch-Site"]).join(", ")
  end
end

#commit_csrf_token(request)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 490

def commit_csrf_token(request) # :doc:
  csrf_token = request.env[CSRF_TOKEN]
  csrf_token_storage_strategy.store(request, csrf_token) unless csrf_token.nil?
end

#compare_with_global_token(token, session = nil) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 779

def compare_with_global_token(token, session = nil) # :doc:
  ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, global_csrf_token(session))
end

#compare_with_real_token(token, session = nil) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 775

def compare_with_real_token(token, session = nil) # :doc:
  ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, real_csrf_token(session))
end

#csrf_token_hmac(session, identifier) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 816

def csrf_token_hmac(session, identifier) # :doc:
  OpenSSL::HMAC.digest(
    OpenSSL::Digest::SHA256.new,
    real_csrf_token(session),
    identifier
  )
end

#decode_csrf_token(encoded_csrf_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 895

def decode_csrf_token(encoded_csrf_token)
  Base64.urlsafe_decode64(encoded_csrf_token)
end

#encode_csrf_token(csrf_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 891

def encode_csrf_token(csrf_token)
  Base64.urlsafe_encode64(csrf_token, padding: false)
end

#form_authenticity_param (private)

The form’s authenticity parameter. Override to provide your own.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 836

def form_authenticity_param # :doc:
  params[request_forgery_protection_token]
end

#form_authenticity_token(form_options: {}) (private)

Creates the authenticity token for the current request.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 710

def form_authenticity_token(form_options: {}) # :doc:
  masked_authenticity_token(form_options: form_options)
end

#generate_csrf_token (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 887

def generate_csrf_token
  SecureRandom.urlsafe_base64(AUTHENTICITY_TOKEN_LENGTH)
end

#global_csrf_token(session = nil) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 812

def global_csrf_token(session = nil) # :doc:
  csrf_token_hmac(session, GLOBAL_CSRF_TOKEN_IDENTIFIER)
end

#handle_unverified_request (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 534

def handle_unverified_request
  protection_strategy = forgery_protection_strategy.new(self)

  if protection_strategy.respond_to?(:warning_message)
    protection_strategy.warning_message = unverified_request_warning_message
  end

  protection_strategy.handle_unverified_request
end

#initialize

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 479

def initialize(...)
  super
  @_marked_for_same_origin_verification = nil
  @_verify_authenticity_token_ran = false
end

#instrument_cross_origin_javascript (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 671

def instrument_cross_origin_javascript
  instrument_csrf_event "csrf_javascript_blocked.action_controller",
    message: CROSS_ORIGIN_JAVASCRIPT_WARNING
end

#instrument_csrf_event(event, message: nil) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 676

def instrument_csrf_event(event, message: nil)
  ActiveSupport::Notifications.instrument event,
    request: request,
    controller: self.class.name,
    action: action_name,
    sec_fetch_site: sec_fetch_site_value,
    message: message
end

#instrument_csrf_token_fallback (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 662

def instrument_csrf_token_fallback
  instrument_csrf_event "csrf_token_fallback.action_controller"
end

#instrument_unverified_request (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 666

def instrument_unverified_request
  instrument_csrf_event "csrf_request_blocked.action_controller",
    message: unverified_request_warning_message
end

#mark_for_same_origin_verification! (private)

GET requests are checked for cross-origin JavaScript after rendering.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 589

def mark_for_same_origin_verification! # :doc:
  @_marked_for_same_origin_verification = request.get?
end

#mask_token(raw_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 768

def mask_token(raw_token) # :doc:
  one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
  encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
  masked_token = one_time_pad + encrypted_csrf_token
  encode_csrf_token(masked_token)
end

#masked_authenticity_token(form_options: {}) (private)

Creates a masked version of the authenticity token that varies on each request. The masking is used to mitigate SSL attacks like BREACH.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 716

def masked_authenticity_token(form_options: {})
  action, method = form_options.values_at(:action, :method)

  raw_token = if per_form_csrf_tokens && action && method
    action_path = normalize_action_path(action)
    per_form_csrf_token(nil, action_path, method)
  else
    global_csrf_token
  end

  mask_token(raw_token)
end

#normalize_action_path(action_path) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 867

def normalize_action_path(action_path)
  uri = URI.parse(action_path)

  if uri.relative? && (action_path.blank? || !action_path.start_with?("/"))
    normalize_relative_action_path(uri.path)
  else
    uri.path.chomp("/")
  end
end

#normalize_relative_action_path(rel_action_path) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 877

def normalize_relative_action_path(rel_action_path)
  uri = URI.parse(request.path)
  # add the action path to the request.path
  uri.path += "/#{rel_action_path}"
  # relative path with "./path"
  uri.path.gsub!("/./", "/")

  uri.path.chomp("/")
end

#per_form_csrf_token(session, action_path, method) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 805

def per_form_csrf_token(session, action_path, method) # :doc:
  csrf_token_hmac(session, [action_path, method.downcase].join("#"))
end

#real_csrf_token(_session = nil) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 797

def real_csrf_token(_session = nil) # :doc:
  csrf_token = request.env.fetch(CSRF_TOKEN) do
    request.env[CSRF_TOKEN] = csrf_token_storage_strategy.fetch(request) || generate_csrf_token
  end

  decode_csrf_token(csrf_token)
end

#request_authenticity_tokens (private)

Possible authenticity tokens sent in the request.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 705

def request_authenticity_tokens # :doc:
  [form_authenticity_param, request.x_csrf_token]
end

#reset_csrf_token(request)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 485

def reset_csrf_token(request) # :doc:
  request.env.delete(CSRF_TOKEN)
  csrf_token_storage_strategy.reset(request)
end

#sec_fetch_site_value (private)

Returns the normalized value of the Sec-Fetch-Site header.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 691

def sec_fetch_site_value # :doc:
  if value = request.headers["Sec-Fetch-Site"]
    value.to_s.downcase.presence
  end
end

#unmask_token(masked_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 761

def unmask_token(masked_token) # :doc:
  # Split the token into the one-time pad and the encrypted value and decrypt it.
  one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
  encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
  xor_byte_strings(one_time_pad, encrypted_csrf_token)
end

#unverified_request_warning_message (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 550

def unverified_request_warning_message
  if !valid_request_origin?
    "HTTP Origin header (#{request.origin}) didn't match request.base_url (#{request.base_url})"
  elsif sec_fetch_site_value == "cross-site"
    "Sec-Fetch-Site header (cross-site) indicates a cross-site request"
  elsif using_header_only_for_forgery_protection?
    "Sec-Fetch-Site header is missing or invalid (#{sec_fetch_site_value.inspect})"
  else
    "Can't verify CSRF token authenticity."
  end
end

#valid_authenticity_token?(session, encoded_masked_token) ⇒ Boolean (private)

Checks the client’s masked token to see if it matches the session token. Essentially the inverse of #masked_authenticity_token.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 731

def valid_authenticity_token?(session, encoded_masked_token) # :doc:
  if !encoded_masked_token.is_a?(String) || encoded_masked_token.empty?
    return false
  end

  begin
    masked_token = decode_csrf_token(encoded_masked_token)
  rescue ArgumentError # encoded_masked_token is invalid Base64
    return false
  end

  # See if it's actually a masked token or not. In order to deploy this code, we
  # should be able to handle any unmasked tokens that we've issued without error.

  if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
    # This is actually an unmasked token. This is expected if you have just upgraded
    # to masked tokens, but should stop happening shortly after installing this gem.
    compare_with_real_token masked_token

  elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
    csrf_token = unmask_token(masked_token)

    compare_with_global_token(csrf_token) ||
      compare_with_real_token(csrf_token) ||
      valid_per_form_csrf_token?(csrf_token)
  else
    false # Token is malformed.
  end
end

#valid_per_form_csrf_token?(token, session = nil) ⇒ Boolean (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 783

def valid_per_form_csrf_token?(token, session = nil) # :doc:
  if per_form_csrf_tokens
    correct_token = per_form_csrf_token(
      session,
      request.path.chomp("/"),
      request.request_method
    )

    ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, correct_token)
  else
    false
  end
end

#verify_authenticity_token (private)

This method is for internal use only.
[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 496

def verify_authenticity_token # :nodoc:
  # This method was renamed to verify_request_for_forgery_protection, to more accurately
  # reflect its purpose now that an authenticity token is not necessarily verified.
  # However, because many people rely on `skip_before_action :verify_authenticity_token`,
  # to opt out of forgery protection, we need to keep this working and deprecate it.
  # We simply mark it as run, as part of protect_from_forgery, and when verifying the
  # request, we check if the method ran. If it didn't, it's because it was skipped
  # on its own and not via skip_forgery_protection, so we can emit the deprecation warning
  @_verify_authenticity_token_ran = true
end

#verify_request_for_forgery_protection (private)

The actual before_action that is used to verify the request to protect from forgery. Don’t override this directly. Provide your own forgery protection strategy instead. If you override, you’ll disable same-origin