CSRF (Cross-Site Request Forgery) is a type of attack where a malicious website tricks a user's browser into making an unwanted request to a different site where the user is authenticated (like submitting a form or triggering an action without consent).
Example of a CSRF Attack
Imagine a user is logged in to bank.com, and visits a malicious site that silently submits:
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Example 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