Skip to main content

Lesson 7 of 8

ANTIFORGERY Tokens & CSRF Protection

CSRF (Cross-Site Request Forgery) tricks an authenticated browser into making requests to your API. For APIs using cookie authentication (rather than Authorization: Bearer), CSRF is a real threat. ASP.NET Core's antiforgery middleware generates synchronized tokens.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Antiforgery for Cookie-Based Auth

Antiforgery for Cookie-Based Auth
using Microsoft.AspNetCore.Antiforgery;

// ━━ Antiforgery registration ━━
builder.Services.AddAntiforgery(options =>
{
    options.HeaderName = "X-CSRF-TOKEN";    // custom header name
    options.Cookie.Name = "csrf";           // CSRF session cookie (not httpOnly!)
    options.Cookie.SameSite = SameSiteMode.Strict;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

// ━━ Generate CSRF token for SPA ━━
app.MapGet("/api/antiforgery/token", (IAntiforgery antiforgery, HttpContext ctx) =>
{
    var tokens = antiforgery.GetAndStoreTokens(ctx);
    // Client reads this, stores in memory, sends as X-CSRF-TOKEN on state-changing requests
    return Results.Ok(new { token = tokens.RequestToken! });
});

// ━━ Validate CSRF on state-changing requests ━━
// Method 1: Attribute (MVC controllers)
[ValidateAntiForgeryToken]
[HttpPost]
public IActionResult Create() => Ok();

// Method 2: Middleware for all non-GET requests
app.UseAntiforgery(); // validates X-CSRF-TOKEN header automatically

// Method 3: Programmatic (Minimal APIs)
app.MapPost("/api/documents", async (IAntiforgery antiforgery, HttpContext ctx) =>
{
    await antiforgery.ValidateRequestAsync(ctx); // throws AntiforgeryValidationException on failure
    return Results.Ok();
});

// ━━ Why Bearer tokens don't need CSRF ━━
// Authorization: Bearer tokens are NOT sent automatically by browsers
// Only cookies are sent automatically (that's what makes CSRF possible)
// If your API uses ONLY Bearer tokens in Authorization header → no CSRF needed
// If your API uses cookie auth (httpOnly access token) → CSRF protection required

IApplicationBuilder app = null!;

Tip

Tip

Practice ANTIFORGERY Tokens CSRF Protection in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of ANTIFORGERY Tokens CSRF Protection from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with ANTIFORGERY Tokens CSRF Protection is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done