ASP.NET Core  

Cross-Site Request Forgery (CSRF) Protection in ASP.NET Core

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 Attack: When a malicious website or script causes a logged-in user’s browser to send unauthorized requests to a trusted site.

  • Key Requirement: The victim must be authenticated, and their session cookies automatically included in the forged request.

  • Impact: Unauthorized fund transfers, email changes, password resets, or privilege escalation.

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

  • Generated by the server and sent to the client.

  • Validated on each request to ensure authenticity.

  • Tokens are unique per user session and request context.

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.

  • Prefer JWT (Bearer tokens) in headers instead of cookies.

  • If cookies are used, implement SameSite and anti-forgery tokens.

6. SameSite Cookies

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

  • Strict: Cookies sent only in first-party contexts.

  • Lax (default): Cookies sent on same-site requests and top-level GET navigations.

  • None (with Secure flag): Cookies sent in all contexts (cross-site).

Example configuration in Program.cs:

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

Best Practices

  • Always use @Html.AntiForgeryToken() in forms.

  • Use [AutoValidateAntiforgeryToken] globally.

  • Include tokens in AJAX requests.

  • Use SameSite cookies wherever possible.

  • Prefer token-based authentication (JWT) for APIs.

  • Educate developers to never disable CSRF protection in production.

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.