[ASP.NET Core] Auto Anti-forgery Token

There is a way to automatically apply ValidateAntiForgeryToken to every Post Action in your controller

You have probably heard of Cross-site Request Forgery (CSRF) attacks. Simply put, the Server executes a forged request coming from a hacker but carrying some user’s genuine authentication. This is very easy to pull off. Say you visit some forum that contains javascript forging a request to your bank asking for a transfer. If you are still signed in to your ebanking account and the bank applies no protection whatsoever, then with a snap of the fingers your money has moved into the hacker’s pocket.

ASP.NET already implements a way for you to fight this attack method, and they call it the Anti-forgery Token

Default protection with ASP.NET Core 2

With ASP.NET Core 2, every time you use a form tag, asp.net automatically inserts the anti-forgery token for you

On the condition that: the form tag has the attribute method="post"

AND

  • the action attribute has no data: action=""
    OR
  • the action attribute is absent

Next, you have to add the [ValidateAntiForgeryToken] attribute to the action that receives the posted data

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account)
{
    // Do something here
}

Auto protection with ASP.NET Core 2

With the approach above, you have to add [ValidationAntiForgeryToken] by hand to every Action that takes a Post request

Asp.net Core introduces a new class that automates this

If you want it automatic per Controller

[Authorize]
[AutoValidateAntiforgeryToken]
public class ManageController : Controller
{
    // Your code here
}

If you want it applied to the whole app

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

That’s it