How to fix Security Misconfiguration
in .NET 8 Web API
Executive Summary
Default .NET 8 templates are a reconnaissance goldmine. If you're running Swagger in production, leaking detailed stack traces, or using wildcard CORS policies, you're basically handing the keys to your kingdom to any script kiddie with a proxy. Security misconfiguration is the low-hanging fruit of the OWASP Top 10; stop making it easy for us.
The Vulnerable Pattern
var builder = WebApplication.CreateBuilder(args); var app = builder.Build();// VULNERABILITY: Swagger UI exposed in production for recon app.UseSwagger(); app.UseSwaggerUI();
// VULNERABILITY: Detailed stack traces leaked to attackers app.UseDeveloperExceptionPage();
// VULNERABILITY: Wildcard CORS allows any site to read API data app.UseCors(policy => policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.MapGet(“/secret”, () => “AdminData”); app.Run();
The Secure Implementation
The fix enforces a 'Secure by Default' posture. First, we wrap Swagger and DeveloperExceptionPage inside an IsDevelopment() check to prevent metadata leakage and stack trace disclosure in production. Second, we replace the wildcard CORS policy with a named policy restricted to trusted origins, mitigating cross-origin data exfiltration. Third, we implement UseHsts() and HttpsRedirection to ensure encrypted transit. Finally, we manually inject essential security headers (X-Frame-Options, CSP, X-Content-Type-Options) to protect against clickjacking, MIME-sniffing, and XSS attacks.
var builder = WebApplication.CreateBuilder(args);// Hardening CORS: Define specific allowed origins builder.Services.AddCors(options => { options.AddPolicy(“SecurePolicy”, policy => { policy.WithOrigins(“https://trusted-app.com”) .AllowAnyMethod() .AllowAnyHeader(); }); });
var app = builder.Build();
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); app.UseDeveloperExceptionPage(); } else { // Production Hardening app.UseExceptionHandler(“/error”); app.UseHsts(); // Force HTTPS with HSTS }
app.UseHttpsRedirection(); app.UseCors(“SecurePolicy”);
// Manual Security Headers app.Use(async (context, next) => { context.Response.Headers.Append(“X-Content-Type-Options”, “nosniff”); context.Response.Headers.Append(“X-Frame-Options”, “DENY”); context.Response.Headers.Append(“Content-Security-Policy”, “default-src ‘self’”); await next(); });
app.MapGet(“/secret”, () => “AdminData”); app.Run();
Your .NET 8 Web API API
might be exposed to Security Misconfiguration
74% of .NET 8 Web API apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.
Free Tier • No Credit Card • Instant Report
Verified by Ghost Labs Security Team
This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.