Web security is more important than ever, especially as attackers get smarter. In this post, you’ll learn how to protect your .NET 8 application against CSRF and XSS attacks using built-in .NET features, middleware, and coding best practices.
CSRF (Cross-Site Request Forgery) Protection
What is CSRF?
CSRF tricks an authenticated user into unknowingly submitting a request to a web application, potentially changing user data or performing unauthorized actions.
How .NET 8 Protects Against CSRF
ASP.NET Core (including .NET 8) provides built-in CSRF protection using anti-forgery tokens, primarily for unsafe HTTP methods (POST, PUT, DELETE).
What are the Step-by-Step Guide to Enable CSRF Protection?
Use Razor Pages / MVC with AntiForgeryToken
<form asp-controller="Account" asp-action="UpdateEmail" method="post"> @Html.AntiForgeryToken() <input type="email" name="newEmail" required /> <button type="submit">Update Email</button></form>
Validate the token on POST action
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateEmail(string newEmail)
{ // Update logic return Ok();
}
The [ValidateAntiForgeryToken] attribute ensures that the token is checked and rejects any request without a valid token.
For APIs: Use SameSite Cookies + Custom Header Tokens
CSRF tokens don’t apply well to APIs (since many use application/json requests without forms), so for Web APIs, consider:
- Use SameSite cookies: Prevent cookies from being sent cross-origin.
- Require a custom header to confirm origin.
services.Configure<CookiePolicyOptions>(options =>{ options.MinimumSameSitePolicy = SameSiteMode.Strict;
});
On the client, send a custom header (e.g., X-CSRF-TOKEN) that is validated server-side.
[HttpPost]
public IActionResult SecureApi([FromHeader(Name = "X-CSRF-TOKEN")] string csrfToken)
{ if (csrfToken != expectedToken) { return Unauthorized(); } return Ok("Secure call");
}
Use middleware or filters to validate CSRF headers globally.
XSS (Cross-Site Scripting) Protection
What is XSS?
XSS attack is injecting malicious scripts into trusted content. These scripts can steal cookies, log keystrokes, or hijack sessions.
Preventing XSS in .NET 8
.NET automatically HTML-encodes Razor output — but you still need to follow output encoding, input validation, and content security policies (CSP).
Razor Pages / Views: HTML Encoding by Default
<p>@Model.UserComment</p> <!-- Safe: encoded by default -->
Avoid using @Html.Raw() unless absolutely necessary and only on trusted content.
Server-side Validation and Sanitization
Use regex or libraries to sanitize input:
if (Regex.IsMatch(comment, @"<script>", RegexOptions.IgnoreCase))
{ ModelState.AddModelError("Comment", "Script tags are not allowed.");
}
Or sanitize using a library like HtmlSanitizer:
dotnet add package Ganss.XSS
var sanitizer = new HtmlSanitizer();
string safeHtml = sanitizer.Sanitize(userInput);
Add HTTP Security Headers
Use middleware to add headers like:
- Content-Security-Policy
- X-Content-Type-Options
X-XSS-Protection (deprecated but still good for older browsers)
app.Use(async (context, next) =>{ context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'"); context.Response.Headers.Add("X-Content-Type-Options", "nosniff"); await next();
});
CSP (Content Security Policy) Example
This prevents inline script execution unless specifically allowed:
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;
Don’t Allow HTML in User Input (If Not Needed)
If your site doesn’t need to render raw HTML, strip it out completely:
var clean = Regex.Replace(userInput, "<.*?>", string.Empty);
Test Your Protection
Use tools like:
- OWASP ZAP or Burp Suite – Penetration testing
- Postman – Simulate CSRF/XSS
- Chrome DevTools – Test SameSite behavior
Secure Your .NET 8 App From Common Attacks
Threat | Defense |
CSRF | AntiForgeryToken, SameSite cookies, custom headers |
XSS | HTML encoding, sanitizing input, CSP headers, avoid using @Html.Raw() |
Conclusion
Protecting your .NET 8 app from CSRF and XSS is not just about writing secure code, but also about configuring your application correctly. With built-in tools like AntiForgeryToken, HTML encoding in Razor, and custom middleware for headers, .NET gives you a solid base — but you must implement these correctly.