What is CSRF and how do you prevent it in ASP.NET?
What is CSRF and how do you prevent it in ASP.NET?
Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM
17-Jun-2025Example of a CSRF Attack
Imagine a user is logged in to
bank.com, and visits a malicious site that silently submits:If the site doesn't verify the request origin, the bank may wrongly honor the request.
How to Prevent CSRF in ASP.NET (MVC or Core)
1. Use Anti-Forgery Tokens
ASP.NET MVC and Core provide built-in anti-forgery token mechanisms.
In Razor Views:
In Controller:
2. For Web APIs
For APIs (which don’t use cookies by default), CSRF is less common unless using cookie-based auth. If so:
Require clients to send an anti-CSRF token via a custom header (e.g.
X-CSRF-TOKEN)Validate it manually or using middleware
3. Use
SameSiteCookie AttributeIn
.NET Core, set your auth cookie to:This prevents browsers from sending cookies on cross-site requests.
4. Disable Cross-Origin for Unsafe Methods
GETrequests from cross-origin sources.POST,PUT,DELETE, etc. using CORS unless you explicitly trust the source.Summary
@Html.AntiForgeryToken()[ValidateAntiForgeryToken]SameSite=Strict