Hardens API security with rate limiting, input validation, security headers, CORS, and protection against common attacks. Guides through auditing endpoints, configuring headers, and implementing rate limiting.
Ships in claude-skills-collection. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
/swagger, logs, code).curl -sI https://api.example.com/health | grep -iE "server|x-powered|access-control|x-content"
Critère de décision : si un endpoint peut être appelé sans jeton ou sans vérification d'ownership sur la ressource → priorité 1.
// Program.cs — avant app.UseRouting()
app.Use(async (context, next) =>
{
var headers = context.Response.Headers;
headers.Append("X-Content-Type-Options", "nosniff");
headers.Append("X-Frame-Options", "DENY");
headers.Append("X-XSS-Protection", "0"); // désactivé volontairement (géré par CSP)
headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
headers.Append("Content-Security-Policy", "default-src 'self'");
headers.Append("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
headers.Append("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
headers.Remove("Server");
headers.Remove("X-Powered-By");
headers.Remove("X-AspNet-Version");
await next();
});
Vérifier après déploiement avec securityheaders.com ou
curl -sI.
Critères de choix :
FixedWindow large (ex. 100 req/min par IP)SlidingWindow strict (ex. 5–10 req/min)TokenBucket ou blocage complet hors IP whitelist// .NET 7+ — Microsoft.AspNetCore.RateLimiting
builder.Services.AddRateLimiter(options =>
{
// Global : 100 req/min par IP
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(ctx =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1)
}));
// Politique "strict" pour endpoints sensibles
options.AddPolicy("strict", ctx =>
RateLimitPartition.GetSlidingWindowLimiter(
partitionKey: ctx.User.Identity?.Name // par utilisateur si authentifié
?? ctx.Connection.RemoteIpAddress?.ToString()
?? "anon",
factory: _ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 6
}));
options.OnRejected = async (ctx, token) =>
{
ctx.HttpContext.Response.StatusCode = 429;
ctx.HttpContext.Response.Headers.Append("Retry-After", "60");
await ctx.HttpContext.Response.WriteAsync("Too Many Requests", token);
};
});
app.UseRateLimiter();
// Sur l'endpoint
app.MapPost("/api/payments", handler).RequireRateLimiting("strict");
Validation d'entrée (DTO) :
public class CreatePaymentRequest
{
[Required]
[Range(1, 9_999_999)]
public int AmountCents { get; set; }
[Required, RegularExpression("^(EUR|USD|MAD|TND)$")]
public string Currency { get; set; } = default!;
[Required, StringLength(50, MinimumLength = 1)]
[RegularExpression("^[a-zA-Z0-9_-]+$")] // pas d'injection possible
public string RecipientId { get; set; } = default!;
[MaxLength(10)]
public Dictionary<string, string>? Metadata { get; set; }
}
BOLA — vérification d'ownership :
// Toujours filtrer par UserId de la session, pas par paramètre URL seul
var order = await db.Orders
.Where(o => o.Id == orderId && o.UserId == currentUserId) // double filtre obligatoire
.FirstOrDefaultAsync();
if (order is null) return Results.NotFound(); // ne pas révéler l'existence
Réponses d'erreur génériques :
// Anti-pattern : retourner le message d'exception
return Results.Problem(ex.Message); // ❌ fuite d'info
// Correct
return Results.Problem("Une erreur est survenue.", statusCode: 500); // ✅
// Logger ex en interne avec correlation ID
CORS strict :
builder.Services.AddCors(options =>
{
options.AddPolicy("Production", policy =>
policy.WithOrigins("https://app.company.com", "https://admin.company.com")
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Authorization", "Content-Type", "X-Correlation-Id")
.SetMaxAge(TimeSpan.FromHours(1))); // cache preflight 1h
});
// Jamais AllowAnyOrigin() + AllowCredentials() ensemble → erreur runtime + faille critique
Logging sécurité (Serilog / ILogger) :
// Événements à logger systématiquement
logger.LogWarning("Auth failed: user={User} ip={Ip} endpoint={Ep}", user, ip, path);
logger.LogWarning("Rate limit hit: ip={Ip} policy={Policy}", ip, policy);
logger.LogWarning("BOLA attempt: requestedId={Id} ownerId={Owner}", id, owner);
Envoyer ces logs vers un SIEM ou au moins un fichier séparé consultable en cas d'incident.
| # | Risque | Contrôle minimal |
|---|---|---|
| API1 | Broken Object Level Authorization | Filtre UserId sur chaque requête DB |
| API2 | Broken Authentication | JWT exp court (15 min), refresh rotation, révocation |
| API3 | Broken Object Property Level Authorization | DTO explicites, jamais d'entités directes |
| API4 | Unrestricted Resource Consumption | Rate limit + pagination obligatoire (maxPageSize) |
| API5 | Broken Function Level Authorization | [Authorize(Roles="Admin")] sur chaque endpoint admin |
| API6 | Unrestricted Sensitive Business Flows | Limites métier (ex. max 3 OTP/24h), CAPTCHA |
| API7 | Server Side Request Forgery | Whitelist d'URLs, interdire les IPs privées dans les webhooks |
| API8 | Security Misconfiguration | Headers corrects, swagger désactivé en prod, erreurs génériques |
| API9 | Improper Inventory Management | Inventaire d'endpoints versionné, décommissionner /v1 obsolètes |
| API10 | Unsafe Consumption of APIs | Valider le schéma des réponses tierces, timeout agressif |
AllowAnyOrigin().AllowCredentials() : interdit par la spec CORS et par ASP.NET Core — exception au démarrage.UseDeveloperExceptionPage() hors Development.exp absent ou très long) : une clé volée reste valide indéfiniment.?orderBy=DROP TABLE → injection si non validé.?pageSize=999999 → DoS.* sur une API avec Authorization : les cookies/tokens ne sont pas envoyés dans ce cas, mais la config reste dangereuse si évolution future.# Tester les headers en prod
curl -sI https://api.example.com/ | grep -iE "strict-transport|content-security|x-content|server"
# Tester CORS
curl -sI -X OPTIONS https://api.example.com/api/payments \
-H "Origin: https://evil.com" \
-H "Access-Control-Request-Method: POST" | grep -i "access-control"
# Tester le rate limit (10 appels rapides)
for i in {1..12}; do curl -sw "%{http_code}\n" -o /dev/null https://api.example.com/api/auth/login; done
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
api-security, rate-limiting, security-headers, cors, input-validation, owasp
/claude-skills-collection:security-api-security-hardenerfrom claude-skills-collection
npx claudepluginhub vantaflow/claude-skills-collection --plugin claude-skills-collection348 skills in this plugin
/agent-a2a-protocol-guideGuide du protocole Agent-to-Agent (A2A) de Google pour l'interopérabilité entre agents IA — découverte, communication et collaboration inter-agents, avec exemples de code, critères de décision et pièges à éviter. Se déclenche avec "A2A", "agent-to-agent", "protocole A2A", "Google A2A", "interopérabilité agents". Also triggers on "agent-to-agent protocol", "agent interoperability", "connect two agents"./agent-agent-observabilityInstrumentation technique d'un agent IA — tracing distribué des appels LLM et outils, spans, métriques custom, corrélation de logs et dashboards de supervision. Pour les alertes et garde-fous de production, voir agent-monitoring-setup. Se déclenche avec "observabilité agent", "tracing agent", "LangSmith", "Langfuse", "OpenTelemetry agent", "spans LLM", "corréler les logs agent". Also triggers on "trace my agent", "LLM tracing", "agent spans"./agent-api-caller-subagentSous-agent spécialisé dans les appels API REST/GraphQL avec retry, auth et transformation de données. Se déclenche avec "sous-agent API", "API caller agent", "agent qui appelle une API", "REST agent", "HTTP agent", "API integration subagent", "external API agent". Also triggers on "subagent that calls an API", "API calling agent", "agent HTTP requests".Other plugins' skills for the same job