Overview
Preventing injection, broken auth, and XSS in ASP.NET Core with real code examples and automated scanning.
Injection Prevention
SQL injection remains the #1 vulnerability in web applications. In .NET, parameterised queries via EF Core or ADO.NET prevent it entirely. Never concatenate user input into SQL strings.
For NoSQL databases like Cosmos DB and MongoDB, use typed LINQ queries rather than raw query strings.
// BAD: SQL injection risk
var sql = $"SELECT * FROM Users WHERE Email = '{email}'";
// GOOD: Parameterised via EF Core
var user = await ctx.Users
.Where(u => u.Email == email)
.FirstOrDefaultAsync();
// GOOD: Parameterised raw SQL
var user = await ctx.Users
.FromSqlRaw("SELECT * FROM Users WHERE Email = {0}", email)
.FirstOrDefaultAsync();Broken Authentication
Use ASP.NET Core Identity with modern password hashing (PBKDF2 with 600,000 iterations), enforce MFA, implement account lockout, and rotate refresh tokens on every use.
For API security, validate JWT tokens with strict audience/issuer/lifetime checks. Never trust client-side token validation.
- Enforce minimum password complexity
- Implement account lockout after failed attempts
- Always use HTTPS with HSTS
- Rotate refresh tokens (use refresh token rotation)
- Validate JWT signature, audience, issuer, and expiry
XSS Prevention in Blazor
Blazor Server and WASM are largely immune to XSS because they don't directly manipulate the DOM with raw HTML. However, if you use MarkupString or JavaScript interop with user data, you're exposed.
Always sanitise HTML before using MarkupString. Use the HtmlSanitizer library for server-side cleaning.
- Avoid MarkupString with user-controlled content
- Use Content Security Policy headers
- Enable antiforgery protection on all forms
- Sanitise HTML with HtmlSanitizer before rendering
- Run OWASP ZAP scans in your CI pipeline
Key Takeaways
- EF Core parameterised queries prevent SQL injection by default
- Use ASP.NET Core Identity—don't roll your own auth
- Blazor is XSS-resistant but JavaScript interop can be a vector
- Enable HSTS, CSP, and X-Frame-Options headers
- Automate OWASP ZAP scans in GitHub Actions
Saurav Rai
Founder & Lead Architect, Omni Stack
7+ years building enterprise .NET and cloud applications for clients across Australia, USA, and the Middle East. Passionate about clean architecture, developer experience, and shipping fast.