API Hardening
Core Principles
- Behind a proxy, the app sees the proxy, not the client. Until forwarded headers are configured,
Request.Scheme is http, RemoteIpAddress is the load balancer, HTTPS redirects loop and every client shares one rate-limit bucket. Trust only your own proxies. Trusting every sender lets any client fake its IP with one header.
- Production is not Development. HSTS on, developer exception page off, no exception details in responses, no API explorer UI unless you mean to publish it.
WebApplication turns on the developer page only in Development; keep it that way.
- CORS loosens the browser's rules; it protects nothing. List exact origins from configuration. Credentials never go with a wildcard, and
SetIsOriginAllowed(_ => true) is a wildcard in disguise.
- Cap what one request can cost. A small body limit for JSON and a larger one only on the upload endpoint, so a single request can't tie up memory and bandwidth.
- Code holds the policy, configuration holds the values. Origins, proxy networks and limits differ per environment; the shape of the pipeline does not.
Patterns
The production pipeline, in order
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.ForwardLimit = 1; // one proxy hop; 2 for CDN + load balancer
options.KnownProxies.Clear();
options.KnownIPNetworks.Clear();
foreach (var cidr in builder.Configuration.GetSection("ForwardedHeaders:KnownNetworks").Get<string[]>() ?? [])
options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(cidr)); // e.g. "10.0.0.0/8"
});
builder.Services.AddHsts(options =>
{
options.MaxAge = TimeSpan.FromDays(365);
options.IncludeSubDomains = true;
});
builder.Services.AddProblemDetails();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
var app = builder.Build();
app.UseExceptionHandler(); // ProblemDetails, never a stack trace
app.UseForwardedHeaders(); // before anything that reads scheme, host or client IP
if (!app.Environment.IsDevelopment())
app.UseHsts(); // browsers cache it; keep it off localhost
app.UseHttpsRedirection();
app.UseSecurityHeaders();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
KnownIPNetworks takes System.Net.IPNetwork. The old KnownNetworks property and Microsoft.AspNetCore.HttpOverrides.IPNetwork are obsolete in .NET 10 (warning ASPDEPR005), and the proxy docs page still shows them, so don't copy it. By default only loopback is trusted, so a forgotten proxy network means the headers are silently ignored. In Kubernetes or Azure Container Apps the proxy IP changes; trust the ingress subnet, not one address.
ASPNETCORE_FORWARDEDHEADERS_ENABLED=true turns the middleware on with no proxy restriction. Use it only when the app can't be reached except through the proxy.
Strict CORS for a browser front end
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
builder.Services.AddCors(options => options.AddDefaultPolicy(policy => policy
.WithOrigins(origins) // "https://app.example.com" — no trailing slash
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization", "Content-Type")
.AllowCredentials()));
Use a named policy with .RequireCors("name") when only some endpoints serve the browser. An API called only by servers and mobile apps needs no CORS at all. Leave it out.
HTTP to HTTPS redirects break CORS preflight requests. For a pure API behind TLS-terminating ingress, enforce HTTPS at the ingress and expose only HTTPS from the app, instead of relying on a redirect that API clients won't follow for a POST anyway.
Request body and upload limits
builder.WebHost.ConfigureKestrel(kestrel =>
{
kestrel.Limits.MaxRequestBodySize = 1 * 1024 * 1024; // 1 MB for JSON; the default is ~28.6 MB
kestrel.AddServerHeader = false; // don't advertise the server
});
builder.Services.Configure<FormOptions>(options => options.MultipartBodyLengthLimit = 20 * 1024 * 1024);
internal sealed class UploadAvatarEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/avatar", (IFormFile file, CancellationToken ct) => TypedResults.Ok(file.Length))
.WithMetadata(new RequestSizeLimitAttribute(20 * 1024 * 1024)) // raises the limit for this endpoint only
.DisableAntiforgery() // bearer-token API: no cookie to forge
.RequireAuthorization();
}
Minimal APIs honour RequestSizeLimitAttribute and DisableRequestSizeLimitAttribute metadata. Binding IFormFile adds antiforgery metadata. Without app.UseAntiforgery(), the request fails with a 500. Cookie-authenticated apps add AddAntiforgery() + UseAntiforgery(). Bearer-token APIs call .DisableAntiforgery() on the endpoint. Check the file's type from its content, not its name, and store it outside the web root under a generated name.
ASP.NET Core has no built-in middleware for these (HSTS is the only one), so add a small one:
public static class SecurityHeadersExtensions
{
public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) =>
app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
var headers = context.Response.Headers;
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "no-referrer";
headers.ContentSecurityPolicy = "default-src 'none'; frame-ancestors 'none'";
return Task.CompletedTask;
});
await next(context);
});
}
That CSP fits JSON responses. If the same host serves HTML (an API reference UI, a SPA), give those paths their own policy instead of loosening this one.
Errors without internals
internal sealed class GlobalExceptionHandler(IProblemDetailsService problemDetails, ILogger<GlobalExceptionHandler> logger)
: IExceptionHandler
{
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken ct)
{
logger.LogError(exception, "Unhandled exception for {Path}", context.Request.Path);
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
return await problemDetails.TryWriteAsync(new ProblemDetailsContext
{
HttpContext = context,
Exception = exception,
ProblemDetails = { Title = "Something went wrong.", Extensions = { ["code"] = "server-error" } },
});
}
}
The exception goes to the log, and the response carries only a title, a stable code and the trace ID. In .NET 10, exceptions an IExceptionHandler handles no longer emit diagnostics by default; set ExceptionHandlerOptions.SuppressDiagnosticsCallback if your monitoring relied on them.
Anti-patterns
// BAD — every client can set X-Forwarded-For and become any IP (bypasses IP rate limits, poisons logs)
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
options.ForwardedHeaders = ForwardedHeaders.All;
// and never adding the real proxy back
// GOOD — clear the defaults, then trust only your ingress subnet
options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("10.0.0.0/8"));
// BAD — obsolete in .NET 10 (ASPDEPR005), and ambiguous with System.Net.IPNetwork
options.KnownNetworks.Add(new Microsoft.AspNetCore.HttpOverrides.IPNetwork(System.Net.IPAddress.Parse("10.0.0.0"), 8));
// GOOD
options.KnownIPNetworks.Add(System.Net.IPNetwork.Parse("10.0.0.0/8"));
Wildcard CORS with credentials
// BAD — any site can call the API with the user's cookies
policy.SetIsOriginAllowed(_ => true).AllowCredentials();
// GOOD — exact origins from configuration
policy.WithOrigins(origins).AllowCredentials();
HSTS and developer errors everywhere
// BAD — HSTS pinned on localhost, stack traces in production
app.UseHsts();
app.UseDeveloperExceptionPage();
// GOOD — HSTS outside Development; ProblemDetails for unhandled exceptions
if (!app.Environment.IsDevelopment())
app.UseHsts();
app.UseExceptionHandler();
Raising the global body limit for one upload
// BAD — every JSON endpoint now accepts 200 MB
builder.WebHost.ConfigureKestrel(k => k.Limits.MaxRequestBodySize = 200 * 1024 * 1024);
// GOOD — small global limit, a bigger one on the upload endpoint only
endpoints.MapPost("/import", (IFormFile file) => TypedResults.Ok(file.Length))
.WithMetadata(new RequestSizeLimitAttribute(200 * 1024 * 1024));
Decision Guide
| Scenario | Recommendation |
|---|
| Behind nginx, YARP, an Azure load balancer or ingress | UseForwardedHeaders first, KnownIPNetworks = the proxy subnet |
| CDN in front of a load balancer | Trust both networks, ForwardLimit = 2 |
| Container platform with changing proxy IPs | Trust the ingress subnet; never clear trust and add nothing back |
| Browser SPA on another origin | Named CORS policy with exact origins from config |
| Server-to-server or mobile-only API | No CORS |
| JSON API | Kestrel MaxRequestBodySize around 1 MB |
| File upload endpoint | RequestSizeLimitAttribute on that endpoint, FormOptions.MultipartBodyLengthLimit, .DisableAntiforgery() for bearer APIs |
| HTTPS | TLS at the ingress plus HSTS; UseHsts only outside Development |
| Unhandled exceptions | UseExceptionHandler + AddProblemDetails + IExceptionHandler, details to logs only |
| Security headers | Small middleware: nosniff, DENY, no-referrer, CSP default-src 'none' for JSON |
| Throttling and abuse | Use the rate-limiting skill |
| Users reading each other's data | Use the resource-authorization skill |