api-hardening
БесплатноБез исполняемых скриптовНе проверенProduction hardening for ASP.NET Core 10 APIs: HSTS, forwarded headers behind a proxy (KnownIPNetworks), strict CORS, body and upload limits, security…
от codewithmukesh★ 858 звёзд на GitHubОб этом скилле
API Hardening
Core Principles
- Behind a proxy, the app sees the proxy, not the client. Until forwarded headers are configured,
Request.Schemeishttp,RemoteIpAddressis 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.
WebApplicationturns 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 `IFor
Установить api-hardening в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл 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).
Как установить скилл api-hardening?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл api-hardening запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic