Preventing Common Vulnerabilities in .NET Applications

“Works on my machine” is meaningless if an attacker can drop SQL into a textbox or trick a cookie into another user’s jar. Let’s tour the OWASP Top faults and their bullet-proofing in .NET.

Real-Life Analogy: Castle Defences

A castle needs walls (validation), boiling oil (WAF), a moat (network segregation) and a portcullis (auth). Miss one and invaders stroll in.

1. SQL Injection

  • Fix – always parameterise; in EF Core use LINQ or FromSqlInterpolated.
  • Anti-pattern – string-concatenated $"… WHERE Name='{name}'".

2. Cross-Site Scripting (XSS)

  • Razor encodes @model.Name by default—do not disable.
  • For APIs, apply Content-Security-Policy header via middleware.

3. Cross-Site Request Forgery (CSRF)

  • @Html.AntiForgeryToken() for MVC; for SPAs use SameSite=Lax cookies + double submit.
  • Disable cookies on pure-JWT APIs and use header tokens instead.

4. Broken Authentication

  • Use AddIdentityCore or IdentityServer—never roll your own hash.
  • Enforce 12-char minimum + lockouts + “Have I Been Pwned” API checks.

5. Sensitive Data Exposure

  • Enforce HTTPS via RequireHttpsAttribute + HSTS.
  • Store secrets in Azure Key Vault / AWS Secrets Manager—not appsettings.json.
  • Sweep logs with Serilog Destructure filters to redact PII.

6. Insecure Deserialization

  • Disable TypeNameHandling.All in JSON .NET.
  • Use System.Text.Json; it blocks polymorphic payloads by default.

7. SSRF & File Upload Tricks

  • Whitelist outbound hosts in HttpClient wrapper.
  • Scan uploads with MIME sniffing; store outside webroot.

Security-Headers Middleware

app.Use(async (ctx, next) =>
{
    ctx.Response.Headers["X-Frame-Options"] = "DENY";
    ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
    ctx.Response.Headers["Content-Security-Policy"] =
        "default-src 'self'; frame-ancestors 'none';";
    await next();
});

Dependency Audits

  • Enable dotnet list package --vulnerable in CI.
  • Pin NuGet sources; disallow “floating” versions.

Security Testing Pyramid

  1. Unit tests for validation logic.
  2. Integration tests with malicious payload fixtures.
  3. Dynamic scanning (OWASP ZAP) in staging.

Final Thoughts

Security is a moving target; defence-in-depth wins. Layer frameworks, headers, validation, and secrets management—your castle will withstand the everyday siege while alarms watch for the zero-day.