ASP.NET Core Interview Question #123

What is the purpose of ValidateAntiForgeryToken in MVC?

Routing, Controllers & Model Binding Mid-Level Intermediate

Quick Interview Answer

Anti-forgery protection helps defend browser-based applications against Cross-Site Request Forgery (CSRF), where a malicious site causes a user's browser to submit an unwanted request using the user's existing authentication context.

Detailed Explanation

Anti-forgery protection helps defend browser-based applications against Cross-Site Request Forgery (CSRF), where a malicious site causes a user's browser to submit an unwanted request using the user's existing authentication context.

ASP.NET Core MVC can generate an anti-forgery token in forms and validate it on state-changing requests. The ValidateAntiForgeryToken attribute explicitly requires validation for the decorated action or controller.

Anti-forgery tokens are particularly relevant to cookie-authenticated browser forms. API authentication designs using bearer tokens have different CSRF characteristics and should be assessed according to how credentials are transported.

Code Example

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult DeleteConfirmed(int id)
{
    _service.Delete(id);
    return RedirectToAction(nameof(Index));
}

// Razor form tag helpers normally generate the token:
<form asp-action="DeleteConfirmed" method="post">
    <button type="submit">Delete</button>
</form>