In a Rails controller, what do protect_from_forgery with: :exception, :reset_session and :null_session each do to an unverified POST?
answer
- only one stops the action
- :exception raises InvalidAuthenticityToken
- :reset_session calls reset_session, then the action runs
- :null_session swaps in an empty session and cookie jar
- bare protect_from_forgery picks :null_session
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.
solid answer
~40 sThe strategy is what `verify_authenticity_token` does once a non-GET request fails the check. `with: :exception` raises `ActionController::InvalidAuthenticityToken`, which becomes a 422; it is what `ActionController::Base` runs by default and the right choice for HTML forms. `with: :reset_session` calls `reset_session` and then **lets the action run**, so it only protects state kept in the session. `with: :null_session` also runs the action, but swaps in an empty session, sets the flash to nil and replaces the cookie jar with one that is empty and never writes, so cookie-based sign-in looks absent; it suits an endpoint that also serves token-authenticated clients. Watch the default: a bare `protect_from_forgery` with no `with:` selects `:null_session`, so adding that line to `ApplicationController` quietly downgrades Base's `:exception`.
code
ruby · 14 linesclass ApplicationController < ActionController::Base
# Base already runs protect_from_forgery with: :exception.
# A bare `protect_from_forgery` here would switch every
# controller to :null_session.
end
class PledgesController < ApplicationController
# HTML forms: keep :exception
end
class Api::PledgesController < ApplicationController
# Same-site pages send X-CSRF-Token; kiosks send an API token.
protect_from_forgery with: :null_session
endgo deeper
Recall the three strategy names and that only :exception raises and blocks the request.
Explain what each strategy does to session, flash and cookies, and that the bare macro defaults to :null_session.
Show the production judgement: where :null_session fits a mixed endpoint, why :reset_session fails with cookie-based sign-in, and how a stray macro downgrades a whole app.
Discuss when a custom strategy or token store is worth owning versus keeping the framework default and splitting endpoints.
## Where the strategy fits `protect_from_forgery` installs a `before_action :verify_authenticity_token`. For a GET or HEAD, or when protection is off, nothing happens. For any other method, Rails checks the Origin header (when that check is on) and the submitted token. If the request is **unverified**, Rails logs a warning and instantiates the class held in `forgery_protection_strategy`, calling its `handle_unverified_request`. The `with:` option picks that class. ## The three built-in strategies | `with:` | Class | What happens | Does the action run? | |---|---|---|---| | `:exception` | `ProtectionMethods::Exception` | raises `ActionController::InvalidAuthenticityToken` (422) | no | | `:reset_session` | `ProtectionMethods::ResetSession` | calls the controller's `reset_session` | yes | | `:null_session` | `ProtectionMethods::NullSession` | replaces session, flash and cookie jar for this request | yes | Details worth knowing: - **`:exception`** is the only strategy that stops the request. You can `rescue_from ActionController::InvalidAuthenticityToken` to render something friendlier, but the action itself is skipped. - **`:reset_session`** destroys the session and the stored CSRF token. Anything the action reads from `session` is gone, but other cookies are untouched. - **`:null_session`** sets `request.session` to an empty hash that cannot be destroyed or saved, sets `request.flash` to nil, passes `session_options` `skip: true` so no session cookie is written, and installs an empty cookie jar whose `write` does nothing. The action runs as if the browser had sent no cookies. ## Two traps **The bare call defaults to `:null_session`.** The macro evaluates `options[:with] || :null_session`. `ActionController::Base` gets `:exception` only because the railtie passes it explicitly. A developer who writes a bare `protect_from_forgery` in `ApplicationController`, thinking it is a harmless reminder, replaces the strategy for every controller below it: forged posts now run their actions with an empty session instead of failing. **`:reset_session` protects only what lives in the session.** Rails 8's authentication generator stores the sign-in in a signed, permanent cookie, `cookies.signed[:session_id]`, not in `session`. `reset_session` leaves that cookie alone, so under `:reset_session` a forged request that reaches the app with the cookie still runs as the signed-in user. The generator sets that cookie `same_site: :lax`, which limits when a browser sends it cross-site, but the strategy itself gives no protection. `:null_session` does blank the cookie jar, and `:exception` never runs the action. The security guide makes the same point about persistent cookies: clear them yourself in a `rescue_from` if you rely on them. ## Choosing for a donation platform Picture a donation site with HTML pledge forms and a JSON endpoint that the same site's pages call and that partner kiosks call with an API token in the `Authorization` header: 1. **HTML forms**: keep Base's `:exception`. A failed token should stop the pledge and show an error. 2. **The mixed JSON endpoint**: `protect_from_forgery with: :null_session` in that controller lets the kiosk's token-authenticated call run, because it never relied on cookies, while a forged browser request runs with no cookies and therefore finds no signed-in donor. Your own pages still send `X-CSRF-Token` from `csrf_meta_tags`, so their requests verify and keep their session. 3. **A purely external endpoint** with no browser session at all is better served by skipping protection on that action and authenticating the request another way. Because `forgery_protection_strategy` is class-level configuration, a subclass setting it affects that controller and its descendants only. ## Custom strategies and token storage `with:` also accepts a class. Rails instantiates it with the controller and calls `handle_unverified_request`, so a team can, for example, sign the user out and raise. Since Rails 7.1, `protect_from_forgery store:` chooses where the real token lives: `:session` (the default, the `_csrf_token` session key), `:cookie` (an encrypted, HttpOnly cookie tied to the session id), or any object responding to `fetch`, `store` and `reset`. ## Other options - `only:` / `except:` and `if:` / `unless:` scope the before-action like any callback. - `prepend: true` moves the check to the front of the callback chain; by default it sits where the macro is called, so earlier callbacks such as authentication run first. ## What interviewers check - That only `:exception` prevents the action from running. - That a bare `protect_from_forgery` means `:null_session`. - That `:reset_session` leaves cookie-based sign-ins in place.
- How would you make a failed token on a pledge form show a friendly page instead of the bare 422?Keep `:exception` and add `rescue_from ActionController::InvalidAuthenticityToken` in `ApplicationController`, redirecting back with a flash such as "Your session expired, please try again" or rendering a page with status 422. The action still never runs; only the response changes. If sign-in lives in a persistent cookie, clear it there too.
- Under :null_session, why does a forged request not see the donor signed in, even though the browser sent the sign-in cookie?`NullSession#handle_unverified_request` replaces `request.cookie_jar` with an empty jar built from no cookies, so `cookies.signed[:session_id]` reads nil, and the session is an empty hash. The authentication concern finds no session record and treats the request as anonymous, so it redirects to sign-in or fails authorization instead of acting for the donor.
- All three protect_from_forgery strategies stop the action from running.
- A bare protect_from_forgery uses the :exception strategy.
- :reset_session signs out every user, whatever cookie holds the sign-in.
- :null_session deletes the user's session from the store.
- Adding protect_from_forgery to ApplicationController is a harmless restatement of Base's default.