ASP.NET Core MVC Intermediate

Preventing cross-site request forgery

Cross-site request forgery (CSRF) tricks a signed-in user's browser into submitting a form to your site from another site. Anti-forgery tokens stop it. This lesson explains the attack and shows how ASP.NET Core MVC protects forms and AJAX requests.

How an anti-forgery token protects a form
  1. StartYour page renders a formThe form Tag Helper adds a hidden __RequestVerificationToken
  2. Step 2A matching cookie is setThe browser stores the paired anti-forgery cookie
  3. Step 3User submitsThe form token and the cookie both reach the server
  4. Step 4Server validatesThe token must match the cookie and the signed-in user
  5. EndValid: the action runsMissing or wrong token: 400 Bad Request

A malicious site can make the browser send your cookies, but it cannot read your page, so it cannot know the form token.

The idea in plain words

Browsers send your site's cookies with every request to your site, even when the request is started by a different site. If a user is signed in to your shop and visits an evil page, that page could auto-submit a hidden form to your /account/delete action, and the browser would helpfully attach the sign-in cookie.

An anti-forgery token is a secret value placed in your form that the other site cannot see. The server accepts a POST only if the token is present and matches.

Example: protect every unsafe request

The form Tag Helper adds the token automatically. Validate it on POST actions with an attribute, or better, globally with AutoValidateAntiforgeryToken, which checks every POST, PUT, PATCH and DELETE.

C#
// Program.cs: validate tokens for all unsafe HTTP methods
builder.Services.AddControllersWithViews(options =>
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));

// Or per action
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeleteAccount() { /* ... */ return RedirectToAction("Bye"); }

Example: AJAX requests

For JavaScript requests, read the token from the page and send it in the RequestVerificationToken header.

Razor
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Antiforgery
@{ var token = Antiforgery.GetAndStoreTokens(Context).RequestToken; }

<button id="like" data-token="@token">Like</button>
<script>
  document.getElementById('like').addEventListener('click', async (e) => {
    await fetch('/products/like/5', {
      method: 'POST',
      headers: { 'RequestVerificationToken': e.target.dataset.token }
    });
  });
</script>

Common mistakes

  • Changing data with GET requests, which anti-forgery validation does not cover.
  • Writing forms by hand without the Tag Helper, so no token is added.
  • Turning validation off with [IgnoreAntiforgeryToken] to fix an error instead of sending the token.

Interview question

Why are cookie-authenticated MVC apps vulnerable to CSRF and how do anti-forgery tokens help?

Browsers automatically attach cookies, including authentication cookies, to requests sent to a site, even when another site triggers them, so a malicious page can make a signed-in user's browser perform actions. Anti-forgery tokens add a secret, per-user value to forms that the attacker cannot read due to the same-origin policy. The server rejects state-changing requests whose token is missing or does not match the anti-forgery cookie.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.