skip to content

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%

answer

  1. on since load_defaults 5.0
  2. HMAC of the session token
  3. action path plus method
  4. meta tag carries the global token
  5. masked differently on every render

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.

solid answer

~40 s

Since `load_defaults 5.0`, `config.action_controller.per_form_csrf_tokens` is true. When `form_with` or `button_to` renders, it passes the form's `action` and `method` to `form_authenticity_token`, which computes an HMAC-SHA256 of the session's real token over `"/pledges#post"`-style input and masks it. On submit, Rails accepts a token that matches the global token, the raw real token, or the per-form token recomputed from `request.path` and `request.request_method`. A token copied from the pledge form therefore fails at `/refunds`. `csrf_meta_tags` calls `form_authenticity_token` with no form options, so it carries the **global** token, which any action accepts; that is why scripts and Turbo can use one header everywhere. All of them derive from one session secret, so `reset_session` invalidates every token at once, and each render looks different because of the one-time-pad mask.

code

erb · 10 lines
erb
<%# Per-form token: bound to POST /pledges %>
<%= form_with url: pledges_path do |f| %>
  <%= f.number_field :amount_cents %>
  <%= f.submit "Pledge" %>
  <%# This button posts the pledge token to /refunds and fails %>
  <button formaction="<%= refunds_path %>">Refund</button>
<% end %>

<%# Separate form, separate token, bound to POST /refunds %>
<%= button_to "Refund", refunds_path %>

go deeper

for a junior

Recall that each form's hidden token is tied to where it posts, and that the meta tag token is the one scripts send.

for a middle

Explain the derivation: one session secret, HMAC over path and method for forms, a global HMAC for the meta tag, and masking per render.

for a senior

Diagnose 422s from formaction overrides, rewritten actions, reused hidden fields and session resets, and choose the fix.

for a principal

Weigh what per-form binding buys against the friction it adds to client-side form handling across a team.

## The setting `config.action_controller.per_form_csrf_tokens` decides whether forms get a token tied to where they post. The module's own default is false; the 5.0 step of `load_defaults`, included in every later version, sets it to true, so a Rails 8.1 app has it on. The idea is damage limitation: if one form's token leaks, for example through a page that echoes HTML somewhere it should not, the leaked value cannot be replayed against a different, more dangerous action. ## How the tokens are derived All tokens start from one **real token**, 32 random bytes stored in the session under `_csrf_token` (or in an encrypted cookie when `protect_from_forgery store: :cookie` is used). From it Rails derives: | Token | Derivation | Accepted by | |---|---|---| | global | HMAC-SHA256(real token, `"!real_csrf_token"`) | any action | | per-form | HMAC-SHA256(real token, `"<action path>#<method>"`) | only that path and HTTP method | | real | the stored value itself | any action (kept for older pages) | `masked_authenticity_token` picks the per-form derivation only when `per_form_csrf_tokens` is on **and** both an action and a method were passed. Otherwise it uses the global token. Who passes what: - `form_with` and `form_tag` call `token_tag` with `form_options: { action:, method: }`, so their hidden field carries a **per-form** token. - `button_to` does the same with its URL and method. - `csrf_meta_tags` calls `form_authenticity_token` with no options, so the `csrf-token` meta tag carries the **global** token. JavaScript and Turbo send it as `X-CSRF-Token`, and it works for any endpoint. ## How verification works On a non-GET request, `valid_authenticity_token?` decodes the submitted value and, for a masked token, unmasks it and accepts it if any of these match in constant time: 1. the global token; 2. the real token; 3. the per-form token recomputed from `request.path` (trailing slash removed) and `request.request_method`. A form rendered for `POST /pledges` and submitted to `POST /refunds` fails all three: it is not the global token, not the real token, and its HMAC was computed over a different path. ## Masking Every rendered token is **masked**: Rails XORs it with 32 fresh random bytes and prepends the pad, then Base64-encodes the result. Two renders of the same form show different strings that verify identically. This is why comparing tokens as strings in a test or a cache key is meaningless, and why seeing the value change on each page load is not a bug. ## Things that break per-form tokens - **Changing where a form posts in the browser**: a submit button with a `formaction` attribute, or JavaScript rewriting the form's `action`, sends a per-form token computed for the original path. - **Building one hidden field and reusing it** across forms in a partial, for example by calling `form_authenticity_token` once with one form's options. - **Forms rendered for a different path or method** than they submit to; HTTP method override is fine, because `form_with` computes the token for the overridden method and `request.request_method` reflects it. Fixes: render each form with its real target through `form_with url:`, or have the JavaScript send the global token from the meta tag in `X-CSRF-Token`. ## Session resets Because every token is derived from the real token, `reset_session` deletes it and invalidates every form already on screen. If an app calls `reset_session` at sign-in or sign-out, a donor who does that in one tab and then submits an older form in another tab will see a 422. That is expected behaviour, not a per-form bug. ## What interviewers check - That you can state that per-form tokens are on by default in modern apps and bind path plus method. - That you know the meta-tag token is the global one and why scripts can reuse it. - That you recognise masking and session resets as the causes of tokens that "change" or "expire".

  • Why does the authenticity token in the page source change on every reload even though the session did not change?
    Each render masks the token: Rails XORs it with 32 fresh random bytes and prepends that pad before Base64-encoding. The server unmasks with the pad and compares the result, so every rendered string verifies. The point is that the secret never appears identically in two responses.
  • A Stimulus controller posts to several endpoints; which token should it send, and how?
    Read the `csrf-token` meta tag written by `csrf_meta_tags` and send it as the `X-CSRF-Token` header. That tag carries the global token, which every action accepts, so one value works for all endpoints. A hidden field copied from a form would be a per-form token tied to that form's path and method.

  • The csrf_meta_tags token only works for the form rendered on the same page.
  • A token that changes on every page load means the session is being reset.
  • Per-form tokens are a separate random value stored in the session for each form.
  • Rails 8.1 apps have per_form_csrf_tokens off unless you enable it.
  • Tokens from an earlier tab stay valid after reset_session.

Assumes Rails 8.1 with load_defaults 8.1; per_form_csrf_tokens has defaulted to true since load_defaults 5.0, and store: :cookie exists since 7.1.