跳到正文
FunCoding

api-hardening

Production hardening for ASP.NET Core 10 APIs: HSTS, forwarded headers behind a proxy (KnownIPNetworks), strict CORS, body and upload limits, security headers, no detailed errors. Use for "HSTS", "forwarded headers", "behind nginx", "CORS", "request size limit", "security headers", "harden for production". Do NOT use for auth (use authentication) or throttling (use rate-limiting).

Star
856
分类
安全
许可证
MIT
最近提交
2026年11月29日

skills/api-hardening/SKILL.md

在 GitHub 上查看

API Hardening

Core Principles

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Security headers

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

Trusting forwarded headers from anyone

// 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"));

Using the obsolete forwarded-headers types

// 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

ScenarioRecommendation
Behind nginx, YARP, an Azure load balancer or ingressUseForwardedHeaders first, KnownIPNetworks = the proxy subnet
CDN in front of a load balancerTrust both networks, ForwardLimit = 2
Container platform with changing proxy IPsTrust the ingress subnet; never clear trust and add nothing back
Browser SPA on another originNamed CORS policy with exact origins from config
Server-to-server or mobile-only APINo CORS
JSON APIKestrel MaxRequestBodySize around 1 MB
File upload endpointRequestSizeLimitAttribute on that endpoint, FormOptions.MultipartBodyLengthLimit, .DisableAntiforgery() for bearer APIs
HTTPSTLS at the ingress plus HSTS; UseHsts only outside Development
Unhandled exceptionsUseExceptionHandler + AddProblemDetails + IExceptionHandler, details to logs only
Security headersSmall middleware: nosniff, DENY, no-referrer, CSP default-src 'none' for JSON
Throttling and abuseUse the rate-limiting skill
Users reading each other's dataUse the resource-authorization skill

相似的 Skill

agent-security-hardening

AFaffaan-m/ECC314k近 7 天新增 4,125 个 star

精选

ponytail-audit

审计整个代码库,找出 bug、安全漏洞和性能瓶颈,获得按重要性排序的通俗报告。

DIDietrichGebert/ponytail202k近 7 天新增 4,780 个 star

gstack

GAgarrytan/gstack143k近 7 天新增 636 个 star

精选

security-and-hardening

按 OWASP Top 10 检查输入处理、登录和依赖,加固代码。

ADaddyosmani/agent-skills122k近 7 天新增 1,627 个 star

doubt-driven-development

ADaddyosmani/agent-skills122k近 7 天新增 1,627 个 star

ruview-rvagent

RUruvnet/RuView106k近 7 天新增 693 个 star