ASP.NET - Anti-forgery Token Deep Dive in ASP.NET

Anti-forgery tokens are a core security feature in ASP.NET used to protect web applications from Cross-Site Request Forgery (CSRF) attacks. A CSRF attack occurs when a malicious website tricks a user’s browser into sending an unwanted request to a different website where the user is already authenticated. Since the browser automatically includes authentication cookies, the target application may mistakenly treat the request as legitimate.

Anti-forgery tokens prevent this by ensuring that every state-changing request originates from the legitimate application and not from an external source.


How CSRF Attacks Work

In a typical CSRF scenario, a user logs into a trusted application. Without logging out, they visit a malicious site. That site silently sends a request (such as a form submission or API call) to the trusted application. Because the browser includes authentication cookies automatically, the request appears valid.

For example, a banking application could receive a forged request to transfer money, and without CSRF protection, it may process it.


Concept of Anti-forgery Tokens

ASP.NET solves this problem by using a pair of tokens:

  1. A cookie token stored in the user’s browser

  2. A request token sent with each form or request

Both tokens must match and be valid for the request to be accepted. Since an attacker cannot read the token from the legitimate site due to browser security restrictions, they cannot forge a valid request.


How Anti-forgery Tokens Work Internally

When a page is rendered:

  1. ASP.NET generates a cryptographically secure token.

  2. One part of the token is stored in a cookie.

  3. Another part is embedded in the HTML form as a hidden field.

When the form is submitted:

  1. The browser sends both the cookie and the hidden field token.

  2. The server validates that:

    • Both tokens exist

    • They match

    • They were generated by the server

  3. If validation fails, the request is rejected.

This mechanism ensures that only requests generated by the application itself are processed.


Implementation in ASP.NET Core

Adding Anti-forgery Token in Forms

In Razor views, tokens are automatically included when using form helpers. You can also explicitly add them:

@Html.AntiForgeryToken()

This generates a hidden input field containing the token.


Validating Tokens

To enforce validation, ASP.NET provides attributes:

  • ValidateAntiForgeryToken

  • AutoValidateAntiforgeryToken

Example:

[ValidateAntiForgeryToken]
public IActionResult SubmitForm(Model model)
{
// Process request
}

The request will be rejected if the token is missing or invalid.


Auto Validation Behavior

In ASP.NET Core MVC:

  • POST, PUT, DELETE requests are typically protected

  • GET requests are not validated by default since they should not modify data

You can enforce global validation using:

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

This ensures all unsafe HTTP methods are automatically protected.


Anti-forgery with AJAX Requests

For AJAX calls, the token must be sent manually.

Steps:

  1. Retrieve the token from the page (usually from a hidden field or meta tag)

  2. Include it in request headers

Example:

headers: {
"RequestVerificationToken": token
}

The server then validates this header along with the cookie.


Anti-forgery in APIs

Traditional anti-forgery tokens are less commonly used in APIs because APIs often rely on token-based authentication like JWT.

However, anti-forgery is still relevant when:

  • Cookies are used for authentication

  • The API is consumed by browsers

In such cases, CSRF protection must be enforced.


Token Generation and Security

ASP.NET uses strong cryptographic techniques to generate tokens. These tokens:

  • Are unique per user session

  • Cannot be predicted or reused easily

  • Are tied to the authenticated identity

The system also uses data protection APIs to encrypt and sign tokens, ensuring integrity and confidentiality.


Common Mistakes and Misconfigurations

  1. Disabling validation for convenience
    Skipping validation exposes the application to CSRF attacks.

  2. Using GET requests for sensitive operations
    GET requests should never change data.

  3. Forgetting tokens in AJAX requests
    This leads to validation failures or insecure implementations.

  4. Mixing cookie authentication with APIs without CSRF protection
    This creates vulnerabilities in browser-based API consumption.


Advanced Scenarios

Customizing Token Behavior

You can configure anti-forgery options:

services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
});

This is useful for SPA applications.


Multiple Tabs and Tokens

ASP.NET handles multiple tabs safely because tokens are tied to the session, not individual pages.


SameSite Cookies

Modern browsers support SameSite cookies, which reduce CSRF risks by restricting cross-site cookie sending. However, anti-forgery tokens are still necessary for full protection.


When Anti-forgery is Not Required

Anti-forgery tokens are not needed when:

  • The application uses JWT in Authorization headers

  • Authentication is stateless and not cookie-based

  • The API is not accessed via browsers


Summary

Anti-forgery tokens are essential for protecting ASP.NET applications from CSRF attacks. They work by validating that each request originates from the legitimate application using a secure token pair. Proper implementation involves embedding tokens in forms, validating them on the server, and ensuring coverage for AJAX and browser-based API requests. Misconfigurations can lead to serious vulnerabilities, so understanding both basic and advanced usage is critical for building secure web applications.