How to Prevent CSRF Attacks in ASP.NET Core

By FoxLearn 2/3/2025 8:43:33 AM   97
Cross-site request forgery (CSRF) is a type of attack where a malicious user tricks an authenticated user into performing unwanted actions on a web application.

The attacker exploits the authenticated user’s session to carry out actions on their behalf, potentially causing damage such as making unauthorized purchases or transferring funds from the victim’s account. Let's take a deeper look at how CSRF attacks function and how to protect your ASP.NET Core applications from them.

How Do CSRF Attacks Work?

A CSRF attack targets users who are already authenticated, typically using cookies. Here’s a breakdown of how the attack happens:

Imagine you’re logged into an online shopping website, and the site uses cookies to authenticate you. When you log in, the server sends an authentication cookie to your browser, and as long as your session is active, any request made with that cookie will be trusted by the website.

Now, let’s say an attacker sends you a seemingly legitimate email that appears to come from the shopping site. If you click the link in the email while you're still logged in, the attacker’s website can make unauthorized POST requests to the shopping website, using the authentication cookie your browser sends automatically. For example, the attacker might change your shipping address or make a purchase on your behalf.

This scenario is a CSRF attack, as it takes advantage of the fact that the site trusts your authentication cookie and does not verify that the request originated from your intended session.

Why Are CSRF Attacks Possible?

CSRF attacks are possible because cookies are stored in the browser and automatically sent with every request to a trusted domain. Since cookies are used for authentication, a web app might unintentionally trust requests based solely on the presence of a cookie, without validating the source.

Protecting Against CSRF Attacks in ASP.NET Core

One of the best ways to prevent CSRF attacks in ASP.NET Core is to use anti-forgery tokens. These tokens provide a mechanism to verify that requests originate from the expected source.

When you implement anti-forgery tokens, two pieces of information are sent to the server for each POST request: one as a cookie and one as form data. The server checks that both values match before processing the request. If they don’t, the server will reject the request.

Example 1: Adding Anti-Forgery Tokens in ASP.NET Core

ASP.NET Core Razor Pages and MVC applications already support anti-forgery tokens by default. For a Razor Page, you would add an anti-forgery token in the form tag like this:

<form method="post">
    @Html.AntiForgeryToken()
</form>

At runtime, this generates a hidden field like this:

<input name="__RequestVerificationToken" type="hidden" value="generated_token_value" />

This token must match the token sent in the request cookie. If it doesn’t, the request is considered invalid.

Example 2: Configuring Anti-Forgery in ASP.NET Core

If you're working with a non-MVC ASP.NET Core application, you'll need to manually add the Microsoft.AspNetCore.Antiforgery package and configure it. This can be done in the ConfigureServices method of your Startup class:

services.AddAntiforgery(options => 
{ 
      options.FormFieldName = "MyAntiForgeryField"; 
      options.HeaderName = "MyAntiForgeryHeader"; 
      options.Cookie.Name = "MyAntiForgeryCookie"; 
});

This configuration allows you to customize the names of the form field, header, and cookie used for the anti-forgery token.

Validating Anti-Forgery Tokens

You can also manually validate CSRF tokens in your ASP.NET Core controllers. Here’s how to validate a token programmatically in an action method:

[HttpPost]
public async Task<ActionResult<int>> UpdateOrder(int orderId)
{
    if (!await IsAntiForgeryTokenValid())
        return BadRequest("Invalid CSRF token.");
    
    // Continue with your action logic here...
    return Ok();
}

Here’s the helper method for validating the anti-forgery token:

private async Task<bool> IsAntiForgeryTokenValid()
{
    try
    {
        await antiForgery.ValidateRequestAsync(this.HttpContext);
        return true;
    }
    catch (AntiforgeryValidationException)
    {
        return false;
    }
}

Alternatively, the [AutoValidateAntiforgeryToken] attribute automatically validates the CSRF token for all POST requests.

Example 3: Applying AutoValidateAntiForgeryToken Globally

You can apply the AutoValidateAntiForgeryToken attribute globally for all controllers by adding this in your ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllersWithViews(options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()));
}

Overriding Anti-Forgery Tokens

In certain situations, you might need to override the default behavior for anti-forgery tokens. For instance, you might want to change the name of the token in the cookie or header, or even bypass CSRF protection for certain actions.

Here’s how you can bypass the anti-forgery token validation for specific methods:

[AutoValidateAntiforgeryToken]
public class AccountController : Controller
{
    [HttpPost]
    [IgnoreAntiforgeryToken]
    public IActionResult LoginWithoutToken()
    {
        // This action method will not require an anti-forgery token.
    }
}

Best Practices to Prevent CSRF Attacks

Beyond using anti-forgery tokens, consider the following best practices to further protect your users:

  • Keep your anti-virus software up to date.
  • Avoid storing login credentials in the web browser.
  • Periodically clear browser cookies.
  • Disable scripting in your browser when possible.
  • Implement multi-factor authentication.
  • Log out of applications when not in use.
  • Monitor your devices for malware.

Additionally, remember that CSRF attacks can also target basic and digest authentication, so you must remain vigilant about all authentication methods.

To prevent CSRF attacks in your ASP.NET Core applications, the key is to use anti-forgery tokens. While MVC applications automatically handle these tokens, other types of ASP.NET Core applications require manual setup. By combining anti-forgery tokens with best practices like multi-factor authentication and session management, you can protect your users from these dangerous attacks.