Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core

Antiforgery middleware is added to the Dependency injection container when one of the following APIs is called in Program.cs:

The FormTagHelper injects antiforgery tokens into HTML form elements. The following markup in a Razor file automatically generates antiforgery tokens:

<form method="post">
    <!-- ... -->

Explicitly add an antiforgery token to a <form> element without using Tag Helpers with the HTML helper @Html.AntiForgeryToken:

<form asp-action="Index" asp-controller="Home" method="post">

    <!-- ... -->

In each of the preceding cases, ASP.NET Core adds a hidden form field similar to the following example:

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">

Configure antiforgery with AntiforgeryOptions

Customize AntiforgeryOptions in Program.cs:

builder.Services.AddAntiforgery(options =>
    // Set Cookie properties using CookieBuilder properties†.
    options.FormFieldName = "AntiforgeryFieldname";
    options.HeaderName = "X-CSRF-TOKEN-HEADERNAME";
    options.SuppressXFrameOptionsHeader = false;