liveBook · Manning

CSRF token

As explained in ASP.NET Core in Action, 3e

An antiforgery token is a value paired between a form or request and a browser cookie to verify that a state-changing request originated from the legitimate application.

A CSRF token helps verify that a state-changing request came from the legitimate application, not a malicious site impersonating a logged-in user. The risk is greatest when authentication uses cookies, because browsers send those cookies automatically with requests. section 29.2 section 29.5

A protected form request typically works like this:

  • The application adds a hidden form field containing a random verification value. section 29.5
  • The application stores a related token in a browser cookie. section 29.5
  • A legitimate submission includes both values, while a forged submission generally has only the automatically forwarded cookie. section 29.2 section 29.5
  • Razor Pages adds tokens to Razor-created forms and validates them on inbound requests by default; disabling validation requires deliberate use of [IgnoreAntiForgeryToken]. section 29.5 section 29.2

Protecting a funds-withdrawal form

A banking page might post an amount with a form. A malicious site can imitate that form, but it cannot read the legitimate site's hidden token. A protected form therefore includes a hidden __RequestVerificationToken field alongside the amount; the application rejects a request whose cookie and form tokens do not match. section 29.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains the attack, paired cookie and hidden-field tokens, framework defaults, and an opt-out attribute, but not token-generation internals.
Examples
Uses a banking transfer or withdrawal form with an amount field and a hidden __RequestVerificationToken field.
What it assumes
Assumes cookies and authenticated form submissions, while explaining the attack mechanism and token pairing from the beginning.
What you can do after
Apply it via Razor Pages by retaining default antiforgery validation and recognizing when disabling it requires caution.
How it connects
Connects CSRF tokens with CSRF attacks, cookie-based authentication, Razor Pages, and request validation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.