Cross-Site Request Forgery (CSRF) is a common web application security vulnerability that tricks authenticated users into performing unwanted actions on a web application. For example, if a user is logged into their banking account, a malicious site could attempt to make them unknowingly transfer money.

ASP.NET Core provides built-in mechanisms to prevent CSRF attacks, especially for state-changing requests.

What is CSRF?

CSRF Protection Mechanisms in ASP.NET Core

ASP.NET Core uses anti-forgery tokens to mitigate CSRF. These tokens ensure that the request originated from the same application and not from a malicious third party.

1. Anti-Forgery Tokens

How it works:

  1. The server generates a hidden token and sends it with the form.

  2. When the user submits the form, the token is sent back.

  3. The server validates the token against the user session.

2. Enabling CSRF Protection in Razor Pages / MVC

ASP.NET Core automatically adds CSRF protection for unsafe HTTP methods (POST, PUT, PATCH, DELETE) in Razor Pages and MVC.

Example in Razor view

<form asp-action="TransferFunds" method="post">
    @Html.AntiForgeryToken()
    <input type="text" name="amount" />
    <button type="submit">Transfer</button>
</form>

Controller Action

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult TransferFunds(decimal amount)
{
    // Process transfer safely
    return RedirectToAction("Success");
}

Note: In Razor Pages, antiforgery validation is automatic; you don’t need [ValidateAntiForgeryToken].

3. Global CSRF Protection

You can enforce antiforgery validation globally:

services.AddControllersWithViews(options =>
{
    options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});

This automatically applies CSRF validation to all unsafe HTTP methods, reducing the risk of developer oversight.

4. AJAX and CSRF

When making AJAX requests, you need to include the antiforgery token in the headers.

View

<script>
    var token = '@Antiforgery.GetTokens(HttpContext).RequestToken';
    $.ajax({
        url: '/Funds/Transfer',
        type: 'POST',
        headers: {
            'RequestVerificationToken': token
        },
        data: { amount: 100 }
    });
</script>

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Transfer(decimal amount)
{
    // Transfer funds securely
}

5. Web APIs and CSRF

For stateless APIs, CSRF is less of a concern if you don’t use cookies for authentication.

6. SameSite Cookies

ASP.NET Core sets cookies with SameSite attributes to mitigate CSRF:

Example configuration in Program.cs:

builder.Services.ConfigureApplicationCookie(options =>
{
    options.Cookie.SameSite = SameSiteMode.Lax;
    options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});

Best Practices

Conclusion

Cross-Site Request Forgery is a serious threat that targets authenticated users. ASP.NET Core simplifies CSRF protection by providing built-in anti-forgery tokens, SameSite cookies, and global enforcement mechanisms. By enabling these protections, developers can ensure that malicious actors cannot exploit user trust to perform unauthorized actions.