How to Fix Cross-Site Request Forgery (CSRF) in ASP.NET
Learn how to prevent and fix Cross-Site Request Forgery (CSRF) vulnerabilities in ASP.NET applications. Step-by-step guide with code examples, security checklists, and best practices.
What Is Cross-Site Request Forgery (CSRF)?
Cross-Site Request Forgery (CSRF) is an attack that tricks an authenticated user into submitting a request they did not intend to make. The attack exploits the fact that browsers automatically include cookies (including session cookies) with every request to a domain, regardless of the request's origin.
An attacker crafts a malicious page or email containing a request to the target application. When an authenticated user visits the attacker's page, their browser automatically sends the request along with valid session cookies. The target application cannot distinguish this forged request from a legitimate one. CSRF attacks can change email addresses, transfer funds, modify account settings, or perform any action the authenticated user is authorized to do.
The attack is particularly effective because it does not require the attacker to steal the user's credentials -- it simply leverages the existing authenticated session. Modern single-page applications using token-based authentication (like JWT in headers) are naturally resistant to CSRF since custom headers are not automatically attached to cross-origin requests, but cookie-based authentication remains vulnerable without explicit protections.
Why It Matters
CSRF attacks can have serious consequences because they execute actions with the full authority of the victim user. In financial applications, CSRF can initiate unauthorized transfers. In administrative panels, it can create new admin accounts or change security settings. Because the requests come from the legitimate user's browser with valid authentication, they are difficult to detect and trace. CSRF attacks are also easy to execute at scale -- an attacker can embed the malicious request in a popular website, forum post, or advertising network, potentially affecting thousands of users simultaneously.
How to Fix It in ASP.NET
Implement anti-CSRF tokens: generate a unique, unpredictable token for each user session and include it in every state-changing request. The server validates this token before processing the request. Use the SameSite cookie attribute (set to "Lax" or "Strict") to prevent cookies from being sent with cross-origin requests. Verify the Origin and Referer headers on the server side. Require re-authentication for sensitive operations like changing passwords or email addresses. Use framework-provided CSRF protection (Next.js Server Actions have built-in CSRF protection, Django includes CSRF middleware, Express has csurf). For APIs, prefer token-based authentication sent via custom headers rather than cookies.
ASP.NET-Specific Advice
- Razor syntax auto-encodes output by default. Never use `@Html.Raw()` with unsanitized user content.
- Use Entity Framework with LINQ queries or parameterized SQL. Never use string interpolation in `FromSqlRaw()` calls.
- ASP.NET includes anti-forgery token validation. Use `[ValidateAntiForgeryToken]` on all POST actions and include `@Html.AntiForgeryToken()` in forms.
- Use Data Annotations (`[Required]`, `[StringLength]`, `[RegularExpression]`) and `ModelState.IsValid` for input validation.
ASP.NET Security Checklist for Cross-Site Request Forgery (CSRF)
ASP.NET Security Best Practices
Razor syntax auto-encodes output by default. Never use `@Html.Raw()` with unsanitized user content.
Use Entity Framework with LINQ queries or parameterized SQL. Never use string interpolation in `FromSqlRaw()` calls.
ASP.NET includes anti-forgery token validation. Use `[ValidateAntiForgeryToken]` on all POST actions and include `@Html.AntiForgeryToken()` in forms.
Use Data Annotations (`[Required]`, `[StringLength]`, `[RegularExpression]`) and `ModelState.IsValid` for input validation.
Use ASP.NET Identity for authentication with proper password hashing (PBKDF2 by default). Never implement custom password storage.
Configure HTTPS redirection and HSTS in `Program.cs`. Use `app.UseHttpsRedirection()` and `app.UseHsts()` in production.
Use `[Authorize]` attributes and policy-based authorization for route-level and action-level access control.
Implement rate limiting using ASP.NET Core's built-in `RateLimiter` middleware (available from .NET 7+).
Scan Your ASP.NET App with SafeVibe
Stop guessing if your ASP.NET app is vulnerable to Cross-Site Request Forgery (CSRF). Run an automated penetration test in minutes and get actionable results.
Start Free Scan