Section 3 of 6
Cross-Site Request Forgery (CSRF)
🎯 What You'll Learn
- What is CSRF
- How CSRF attacks work
- Anti-forgery tokens
- Automatic protection
- Manual validation
What is CSRF?
Cross-Site Request Forgery (CSRF) tricks authenticated users into performing unwanted actions. The attacker exploits the user's authenticated session.
How CSRF Works
- User logs into
bank.com - User visits malicious site
evil.com evil.comcontains hidden form that submits tobank.com/transfer- Browser automatically sends cookies (user is authenticated)
- Money transferred without user's knowledge!
Example Attack
HTML
<!-- On evil.com -->
<form action="https://bank.com/transfer" method="post">
<input type="hidden" name="to" value="attacker" />
<input type="hidden" name="amount" value="10000" />
</form>
<script>document.forms[0].submit();</script>
Anti-Forgery Tokens
ASP.NET Core automatically generates and validates anti-forgery tokens.
Automatic Protection (Razor Pages)
Razor Pages (Automatic)
HTML
<form method="post">
<!-- Token automatically added -->
<input type="text" name="Name" />
<button type="submit">Submit</button>
</form>
MVC Controllers
Add Token to Form
HTML
<form asp-action="Create" method="post">
@Html.AntiForgeryToken()
<button type="submit">Submit</button>
</form>
Validate Token
C#
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Product product)
{
return View();
}
Global Anti-Forgery Filter
Apply anti-forgery validation to all POST requests.
Program.cs
C#
builder.Services.AddControllersWithViews(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
AJAX Requests
Get Token in JavaScript
JavaScript
const token = document.querySelector('input[name="__RequestVerificationToken"]').value;
fetch('/api/products', {
method: 'POST',
headers: {
'RequestVerificationToken': token
}
});
Best Practices
- Always use anti-forgery tokens: For state-changing operations
- Use POST for mutations: Never use GET for data changes
- SameSite cookies: Set SameSite=Strict or Lax
- Validate tokens: Use [ValidateAntiForgeryToken]
Key Takeaways
- CSRF: Tricks users into unwanted actions
- Anti-forgery tokens: Prevent CSRF attacks
- Razor Pages: Automatic protection
- MVC: Use @Html.AntiForgeryToken() and [ValidateAntiForgeryToken]
- Global filter: AutoValidateAntiforgeryTokenAttribute