skip to content

Forgery Protection

Rails rejects forged posts with protect_from_forgery, a session or per-form authenticity token, and csrf_meta_tags for scripts. Interviewers ask which strategy fits pages, webhooks and APIs.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails 8.1 app whose ApplicationController never calls protect_from_forgery, what stops a forged POST, and where does the token come from?

level: juniorimportance: must knowfreq 72%

answer

  1. load_defaults switches it on
  2. default_protect_from_forgery, on since 5.2
  3. hidden authenticity_token field from form_with
  4. csrf_meta_tags for the X-CSRF-Token header
  5. test.rb: allow_forgery_protection = false

basics

~10 s

Rails' Action Controller railtie runs protect_from_forgery with: :exception on ActionController::Base because load_defaults sets default_protect_from_forgery. form_with and button_to embed a hidden authenticity_token, csrf_meta_tags exposes one for scripts, and a bad token raises InvalidAuthenticityToken.

solid answer

~40 s

A new Rails 8.1 app runs `config.load_defaults 8.1`, which includes `config.action_controller.default_protect_from_forgery = true` (on since 5.2). When `ActionController::Base` loads, the railtie calls `protect_from_forgery with: :exception`, so every controller inheriting from it gets a `verify_authenticity_token` before_action without a line in `ApplicationController`. GET and HEAD pass; any other method must carry a valid token, either in the `authenticity_token` param that `form_with` and `button_to` write as a hidden field, or in the `X-CSRF-Token` header, which scripts and Turbo fill from the `csrf-token` meta tag that `csrf_meta_tags` writes in the generated layout. A missing or wrong token raises `ActionController::InvalidAuthenticityToken`, which Rails answers with 422. The generated `config/environments/test.rb` sets `allow_forgery_protection = false`, so tests do not exercise it.

code

erb · 11 lines
erb
<%# app/views/layouts/application.html.erb %>
<head>
  <title>Donations</title>
  <%= csrf_meta_tags %>
</head>

<%# app/views/pledges/new.html.erb %>
<%= form_with model: @pledge do |f| %>
  <%= f.number_field :amount_cents %>
  <%= f.submit "Pledge" %>
<% end %>

go deeper

for a junior

Recall that forgery protection is on by default, that form_with adds a hidden authenticity_token, and that csrf_meta_tags in the layout serves scripts.

for a middle

Explain the chain from load_defaults to default_protect_from_forgery to the railtie calling protect_from_forgery with: :exception, and name both token carriers.

for a senior

Show you can diagnose a 422 InvalidAuthenticityToken in production: lost meta tags, stale cached pages, hand-written forms, and why the test suite never catches them.

for a principal

Weigh relying on framework defaults against declaring protection explicitly, and how a team keeps tests from hiding a missing token.

## Where the protection is switched on A Rails 8.1 application generated with `rails new` has an `ApplicationController` that inherits from `ActionController::Base` and contains `allow_browser versions: :modern` and, with import maps, `stale_when_importmap_changes`. It has no `protect_from_forgery` line, yet forged form posts are rejected. The switch lives in configuration: 1. `config/application.rb` calls `config.load_defaults 8.1`. 2. The 5.2 step of `load_defaults`, which every later version includes, sets `config.action_controller.default_protect_from_forgery = true`. 3. Action Controller's railtie registers an `on_load(:action_controller_base)` hook: when that flag is true, it calls `protect_from_forgery with: :exception` on `ActionController::Base` itself. So the check is inherited by every controller under `Base`. Controllers that inherit from `ActionController::API` do not include the forgery-protection module at all, which is a separate topic. ## What `protect_from_forgery` installs The macro adds a `before_action :verify_authenticity_token` and an after-action that guards JavaScript responses. On each request the before-action asks whether the request is verified. It is verified when any of these hold: - the method is **GET or HEAD**, which Rails treats as safe and never checks; - forgery protection is switched off (`allow_forgery_protection` is false, or the session is a disabled null session); - the **Origin check** passes (on by default since load_defaults 5.0) **and** one of the submitted tokens is valid. Rails looks for the token in two places: the request parameter named by `request_forgery_protection_token` (by default `authenticity_token`) and the `X-CSRF-Token` request header. If neither is valid, it logs `Can't verify CSRF token authenticity.` and hands the request to the configured strategy, here `:exception`. ## Where the token comes from The real token is a random value kept in the session under `_csrf_token`. Pages never print it directly; helpers print a masked copy that changes on every render but verifies against the same secret. | Helper | What it writes | Who sends it back | |---|---|---| | `form_with`, `form_tag` | hidden `<input name="authenticity_token">` for non-GET forms | the browser, as a form field | | `button_to` | a small form with the same hidden field | the browser, as a form field | | `csrf_meta_tags` (in the generated layout's `<head>`) | `<meta name="csrf-param" content="authenticity_token">` and `<meta name="csrf-token" content="...">` | your JavaScript or Turbo, as the `X-CSRF-Token` header | | `form_authenticity_token` | the masked token as a string | whatever you build with it | A form built by hand with a raw `<form method="post">` gets no hidden field; it passes only if Turbo intercepts the submission and adds the meta tag's token as a header, and fails as a plain browser post. Passing `authenticity_token: false` to `form_with` deliberately omits it, which is only right for a form that posts to another site. ## What a failure looks like With the `:exception` strategy the request never reaches the action. `ActionController::InvalidAuthenticityToken` is raised, and Action Dispatch's exception wrapper maps it to **422** (`:unprocessable_content` on Rack 3.1 or later). In production the user sees `public/422.html`; in the log you find the warning line plus the exception. The usual everyday causes are: - a layout that lost its `csrf_meta_tags`, so script requests send no header; - a page cached with an old token while the session was reset, for example after sign-out; - a hand-written form without the hidden field, submitted without Turbo. ## The test environment The generated `config/environments/test.rb` contains `config.action_controller.allow_forgery_protection = false`. With it off, `protect_against_forgery?` is false: forms omit the hidden field and the before-action treats every request as verified. Integration and system tests therefore never fail on a missing token, which is convenient and also means they cannot catch one. A test that must prove protection works sets `ActionController::Base.allow_forgery_protection = true` for its duration and restores it afterwards. ## What interviewers check - That you know the protection is **on by default** through `load_defaults`, not because someone wrote the macro. - That you can name the two carriers: the `authenticity_token` field and the `X-CSRF-Token` header fed by `csrf_meta_tags`. - That GET and HEAD are not checked, so state changes belong on other verbs. - That a failure is a 422 with `InvalidAuthenticityToken`, and that tests run with the check off.

  • Why does a page that forgot its token never fail in the Rails test suite?
    The generated `test.rb` sets `config.action_controller.allow_forgery_protection = false`. With it off, `protect_against_forgery?` returns false, form helpers omit the hidden field, and `verify_authenticity_token` treats every request as verified. A test that needs the real behaviour sets `ActionController::Base.allow_forgery_protection = true` and restores the old value in teardown.
  • Protection also runs on GET requests in one case; which one?
    `protect_from_forgery` adds an after-action, `verify_same_origin_request`. When the before-action ran on a GET and the response is JavaScript (`text/javascript` or `application/javascript`) but the request was not an XHR, Rails raises `ActionController::InvalidCrossOriginRequest`. That stops another site from loading your `.js` response through a `<script>` tag and reading data out of it.

  • Without protect_from_forgery in ApplicationController, a Rails app has no CSRF check at all.
  • Rails verifies the authenticity token on GET requests too.
  • csrf_meta_tags is what puts the token into form_with forms.
  • A failed token check in Rails answers 401 Unauthorized.
  • The test environment checks tokens, so passing system tests prove every form carries one.

Assumes Rails 8.1 with load_defaults 8.1; default_protect_from_forgery has been true for new apps since load_defaults 5.2, and 422 is named :unprocessable_content on Rack 3.1 or later.

open as a page

In a Rails controller, what do protect_from_forgery with: :exception, :reset_session and :null_session each do to an unverified POST?

level: middleimportance: must knowfreq 58%

basics

~20 s

:exception raises ActionController::InvalidAuthenticityToken, so the action never runs. :reset_session clears the session and lets the action run. :null_session runs the action with an empty session, no flash and a cookie jar that reads nothing and writes nothing.

open as a page

A payment provider's webhook POSTs to a Rails 8.1 donation app fail with InvalidAuthenticityToken; how should that controller opt out of forgery protection?

level: middleimportance: should knowfreq 48%

basics

~10 s

Add skip_forgery_protection to the webhook controller, scoped with only:, and authenticate each call by verifying the provider's signature over request.raw_post in a before_action. Leave Base's protection on everywhere else.

open as a page

Behind a TLS-terminating proxy, every Rails 8.1 form POST fails with "HTTP Origin header didn't match request.base_url" - which check fires, and how do you fix it?

level: seniorimportance: should knowfreq 32%

basics

~20 s

forgery_protection_origin_check, on since load_defaults 5.0, compares the browser's Origin with request.base_url. Behind a proxy that ends TLS and sends no X-Forwarded-Proto, base_url starts with http://, so the comparison fails. Forward the scheme or set config.assume_ssl.

open as a page

With Rails' per_form_csrf_tokens on, why is a token rendered for one form rejected at another action, while the csrf_meta_tags token works anywhere?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

With per_form_csrf_tokens on, form_with signs each form's token with the session secret over its action path and method, so it verifies only there. csrf_meta_tags passes no form options and gets the global token, valid for any action.

open as a page