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?
answer
- the provider never rendered your form
- skip_forgery_protection, scoped with only:
- skip_before_action :verify_authenticity_token, raise: false
- verify the signature over request.raw_post
- never flip allow_forgery_protection app-wide
basics
~10 sAdd 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.
solid answer
~40 sThe provider's server never loaded a page of yours, so it has no authenticity token and its POST fails Base's default `:exception` check. The fix belongs on that one controller: `skip_forgery_protection only: :create`, which is a wrapper for `skip_before_action :verify_authenticity_token, raise: false`. Skipping the token is only safe because something else proves who sent the request, so add a `before_action` that recomputes the provider's HMAC over `request.raw_post` with a secret from credentials and compares it with `ActiveSupport::SecurityUtils.secure_compare`, answering `head :unauthorized` on a mismatch. Do not set `allow_forgery_protection = false`, which disables the check app-wide, and do not list webhook actions in `protect_from_forgery except:` in `ApplicationController`, which couples the base class to one endpoint.
code
ruby · 18 linesclass Webhooks::PaymentsController < ApplicationController
skip_forgery_protection only: :create
allow_unauthenticated_access only: :create
before_action :verify_signature, only: :create
def create
Donation.capture_from_webhook!(JSON.parse(request.raw_post))
head :ok
end
private
def verify_signature
secret = Rails.application.credentials.dig(:payments, :webhook_secret)
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, request.raw_post)
given = request.headers["X-Signature"].to_s
head :unauthorized unless ActiveSupport::SecurityUtils.secure_compare(expected, given)
end
endgo deeper
Recall that skip_forgery_protection exists and that it should be limited with only: to the webhook action.
Explain what the macro expands to, why raise: false is there, and why a signature check over request.raw_post must replace the token.
Show judgement on the alternatives: why an app-wide switch or a re-declared protect_from_forgery is wrong, and how an unscoped skip widens exposure.
Discuss whether third-party callbacks belong in a separate controller hierarchy with its own authentication contract, and how that is reviewed.
## Why the webhook fails Every controller under `ActionController::Base` inherits `protect_from_forgery with: :exception` from the defaults. A **webhook** is a POST from the payment provider's servers to a URL in your app, announcing for example that a donation was captured. That server never rendered one of your pages, so it cannot send an `authenticity_token` field or an `X-CSRF-Token` header. `verify_authenticity_token` treats the request as unverified and raises `ActionController::InvalidAuthenticityToken`, and the provider sees a 422 and retries. ## The Rails macro for the exemption ```ruby skip_forgery_protection only: :create ``` `skip_forgery_protection(options = {})` is a thin wrapper: ```ruby skip_before_action :verify_authenticity_token, options.reverse_merge(raise: false) ``` Two details matter: - **It accepts the usual callback options**: `only:`, `except:`, `if:`, `unless:`. Scope it to the webhook action so a later `update` on the same controller is still protected. - **`raise: false`** means the call does not raise `ArgumentError` when no `verify_authenticity_token` callback is defined, for example in an app that turned `default_protect_from_forgery` off. A plain `skip_before_action` would raise there. Skipping the before-action also skips the cross-origin JavaScript guard for that action, because that guard only fires when the before-action has marked the request. That is irrelevant for a JSON webhook but worth knowing. ## What replaces the token Removing the forgery check is safe only because the webhook does not rely on a browser cookie: there is no signed-in user whose ambient credentials could be abused. What you still need is **proof the call came from the provider**: 1. Store the provider's signing secret in credentials. 2. In a `before_action`, compute the HMAC the provider documents over `request.raw_post`, the exact body bytes, not re-serialized params. 3. Compare it with the signature header using `ActiveSupport::SecurityUtils.secure_compare`, which runs in constant time. 4. Answer `head :unauthorized` and stop when they differ; a response rendered in a `before_action` halts the chain. If the app uses the authentication generator, add `allow_unauthenticated_access only: :create` as well, or the generated `require_authentication` will redirect the provider to the sign-in page. ## Alternatives and why they are worse | Approach | Effect | Problem | |---|---|---| | `skip_forgery_protection only: :create` | removes the check on one action | none; this is the intended macro | | `protect_from_forgery except: :create` in the webhook controller | re-installs the callback with the macro's default strategy | without `with:` it also switches that controller to `:null_session` | | `protect_from_forgery with: :null_session` | still checks, then runs with an empty session | every webhook logs a CSRF warning, and the intent is hidden | | `config.action_controller.allow_forgery_protection = false` | turns the check off app-wide | every HTML form loses its protection | | Listing webhook actions in `ApplicationController` | central exemption list | the base class now knows about one endpoint's actions | A controller that inherits from `ActionController::API` never had the protection in the first place; whether a webhook controller should use that base is an API-mode question. ## Things that go wrong - **Unscoped skip**: `skip_forgery_protection` with no `only:` on a controller that also has browser-facing actions exempts them all. - **Signature over parsed params**: re-serializing `params` changes key order and whitespace, so valid calls fail; always sign `request.raw_post`. - **Plain `==` comparison**: leaks timing information; use `secure_compare`. - **Trusting the payload without a check**: a skipped forgery check plus no signature check lets anyone mark donations as paid. ## What interviewers check - That you scope the exemption to the action and use the macro built for it. - That you replace the token with a real authentication step. - That you never disable protection globally for one endpoint.
- Why does `protect_from_forgery except: :create` in the webhook controller change more than the exemption?Calling the macro again re-installs `verify_authenticity_token` and reassigns the strategy. With no `with:` it evaluates to `:null_session`, so every other action in that controller now runs forged requests with an empty session instead of raising. `skip_forgery_protection only: :create` removes the callback for one action and leaves the inherited `:exception` strategy alone.
- What does raise: false in skip_forgery_protection protect you from?`skip_before_action` normally raises `ArgumentError` when the named callback was never defined. If an app sets `default_protect_from_forgery` to false, or a controller's ancestors never installed `verify_authenticity_token`, a plain skip would crash at class load. `skip_forgery_protection` passes `raise: false`, so it is a no-op there.
- Set allow_forgery_protection to false so the payment webhook gets through.
- skip_forgery_protection alone makes the webhook safe; no other check is needed.
- Verify the webhook signature over params.to_json instead of the raw body.
- protect_from_forgery except: :create only removes the check for that action.
- skip_forgery_protection skips every before_action in the controller.