Skip to Content Skip to Search

Action Controller Request Forgery Protection

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 ActionController::Base are protected by default with the :exception strategy, which raises an ActionController::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.

Namespace
Methods
A
C
F
G
M
N
P
R
S
U
V
X
Included Modules

Constants

AUTHENTICITY_TOKEN_LENGTH = 32
 
CSRF_TOKEN = "action_controller.csrf_token"
 

Class Public methods

new(...)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 449
def initialize(...)
  super
  @_marked_for_same_origin_verification = nil
  @_verify_authenticity_token_ran = false
end

Instance Public methods

commit_csrf_token(request)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 460
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

reset_csrf_token(request)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 455
def reset_csrf_token(request) # :doc:
  request.env.delete(CSRF_TOKEN)
  csrf_token_storage_strategy.reset(request)
end

Instance Private methods

any_authenticity_token_valid?()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 658
def any_authenticity_token_valid? # :doc:
  request_authenticity_tokens.any? do |token|
    valid_authenticity_token?(session, token)
  end
end

append_sec_fetch_site_to_vary_header()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 551
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

compare_with_global_token(token, session = nil)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 739
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)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 735
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)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 776
def csrf_token_hmac(session, identifier) # :doc:
  OpenSSL::HMAC.digest(
    OpenSSL::Digest::SHA256.new,
    real_csrf_token(session),
    identifier
  )
end

form_authenticity_param()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 796
def form_authenticity_param # :doc:
  params[request_forgery_protection_token]
end

form_authenticity_token(form_options: {})

Creates the authenticity token for the current request.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 670
def form_authenticity_token(form_options: {}) # :doc:
  masked_authenticity_token(form_options: form_options)
end

global_csrf_token(session = nil)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 772
def global_csrf_token(session = nil) # :doc:
  csrf_token_hmac(session, GLOBAL_CSRF_TOKEN_IDENTIFIER)
end

mark_for_same_origin_verification!()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 559
def mark_for_same_origin_verification! # :doc:
  @_marked_for_same_origin_verification = request.get?
end

marked_for_same_origin_verification?()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 566
def marked_for_same_origin_verification? # :doc:
  @_marked_for_same_origin_verification ||= false
end

mask_token(raw_token)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 728
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

non_xhr_javascript_response?()

Check for cross-origin JavaScript responses.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 571
def non_xhr_javascript_response? # :doc:
  %r(\A(?:text|application)/javascript).match?(media_type) && !request.xhr?
end

per_form_csrf_token(session, action_path, method)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 765
def per_form_csrf_token(session, action_path, method) # :doc:
  csrf_token_hmac(session, [action_path, method.downcase].join("#"))
end

protect_against_forgery?()

Checks if the controller allows forgery protection.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 801
def protect_against_forgery? # :doc:
  allow_forgery_protection && (!session.respond_to?(:enabled?) || session.enabled?)
end

real_csrf_token(_session = nil)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 757
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()

Possible authenticity tokens sent in the request.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 665
def request_authenticity_tokens # :doc:
  [form_authenticity_param, request.x_csrf_token]
end

sec_fetch_site_value()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 653
def sec_fetch_site_value # :doc:
  request.headers["Sec-Fetch-Site"].to_s.downcase.presence
end

unmask_token(masked_token)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 721
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

valid_authenticity_token?(session, encoded_masked_token)

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 691
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)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 743
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

valid_request_origin?()

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

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 817
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?()

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.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 590
def verified_request? # :doc:
  request.get? || request.head? || !protect_against_forgery? ||
    (valid_request_origin? && verified_request_for_forgery_protection?)
end

verify_request_for_forgery_protection()

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 <script> verification.

Lean on the protect_from_forgery declaration to mark which actions are due for same-origin request verification. If protect_from_forgery is enabled on an action, this before_action flags its after_action to verify that JavaScript responses are for XHR requests, ensuring they follow the browser’s same-origin policy.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 486
      def verify_request_for_forgery_protection # :doc:
        if @_verify_authenticity_token_ran
          mark_for_same_origin_verification!

          if !verified_request?
            instrument_unverified_request

            handle_unverified_request
          end
        else
          ActiveSupport.deprecator.warn(<<~MSG.squish)
            `verify_authenticity_token` is deprecated and will be removed in a future Rails version.
            To skip forgery protection, use `skip_forgery_protection` instead of skipping `verify_authenticity_token`
            as this won't have any effect in a future Rails version.
          MSG
        end
      end

verify_same_origin_request()

If verify_request_for_forgery_protection was run (indicating that we have forgery protection enabled for this request) then also verify that we aren’t serving an unauthorized cross-origin response.

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 542
def verify_same_origin_request # :doc:
  if marked_for_same_origin_verification? && non_xhr_javascript_response?
    instrument_cross_origin_javascript
    raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
  end
end

xor_byte_strings(s1, s2)

# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 784
def xor_byte_strings(s1, s2) # :doc:
  s2 = s2.dup
  size = s1.bytesize
  i = 0
  while i < size
    s2.setbyte(i, s1.getbyte(i) ^ s2.getbyte(i))
    i += 1
  end
  s2
end