Durcissement de la Sécurité des APIs
Workflow
- Auditer : identifier les failles potentielles (OWASP API Top 10).
- Configurer : headers, CORS, rate limiting.
- Valider : entrées, sorties, authentification.
- Monitorer : logs de sécurité, détection d'anomalies.
OWASP API Top 10 — Checklist
| # |
Risque |
Contrôle |
| 1 |
Broken Object Level Authorization |
Vérifier l'ownership sur chaque ressource |
| 2 |
Broken Authentication |
JWT court, refresh rotation, MFA |
| 3 |
Broken Object Property Level Authorization |
DTO de réponse, pas d'entités directes |
| 4 |
Unrestricted Resource Consumption |
Rate limiting, pagination obligatoire |
| 5 |
Broken Function Level Authorization |
RBAC sur chaque endpoint |
| 6 |
Unrestricted Access to Sensitive Business Flows |
Captcha, anti-bot, limites métier |
| 7 |
Server Side Request Forgery |
Whitelist d'URLs, pas d'URLs utilisateur |
| 8 |
Security Misconfiguration |
Headers, CORS strict, erreurs génériques |
| 9 |
Improper Inventory Management |
Documenter tous les endpoints, décommissionner les anciens |
| 10 |
Unsafe Consumption of APIs |
Valider les réponses des APIs tierces |
Implémentation ASP.NET Core
Headers de sécurité
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("X-XSS-Protection", "0");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
context.Response.Headers.Append("Content-Security-Policy", "default-src 'self'");
context.Response.Headers.Append("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
context.Response.Headers.Remove("Server");
context.Response.Headers.Remove("X-Powered-By");
await next();
});
Rate Limiting
builder.Services.AddRateLimiter(options =>
{
// Rate limit global
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
RateLimitPartition.GetFixedWindowLimiter(
partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1)
}));
// Rate limit par endpoint
options.AddPolicy("strict", context =>
RateLimitPartition.GetSlidingWindowLimiter(
partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
factory: _ => new SlidingWindowRateLimiterOptions
{
PermitLimit = 10,
Window = TimeSpan.FromMinutes(1),
SegmentsPerWindow = 4
}));
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
});
// Usage
app.MapPost("/api/payments", handler).RequireRateLimiting("strict");
Validation d'entrée
public class CreatePaymentRequest
{
[Required]
[Range(1, 99999999, ErrorMessage = "Le montant doit être entre 1 et 99999999 centimes")]
public int Amount { get; set; }
[Required]
[RegularExpression("^(EUR|USD|GBP)$")]
public string Currency { get; set; }
[Required]
[StringLength(100, MinimumLength = 1)]
public string RecipientId { get; set; }
[MaxLength(10)]
public Dictionary<string, string>? Metadata { get; set; }
}
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")
.SetMaxAge(TimeSpan.FromHours(1));
});
});
Règles
- Ne jamais exposer les entités de base de données directement — toujours des DTOs.
- Les messages d'erreur ne doivent jamais révéler des détails d'implémentation.
- Chaque endpoint doit vérifier l'autorisation (pas seulement l'authentification).
- Le rate limiting doit être appliqué avant la logique métier.
- Logger les tentatives d'accès non autorisées pour la détection d'intrusion.
Ce skill est un outil de sécurité défensif. Il aide à protéger les APIs contre les attaques courantes.
Communication Rules — MANDATORY
- Ultra-concise. No filler, no preamble, no pleasantries.
- Never say "happy to help", "sure!", "great question", "let me", or similar.
- Tool first, talk second. Act before explaining.
- Result first. Lead with outcome, not process.
- Stop when done. No summary, no recap, no trailing commentary.
- No politeness wrappers. Direct and blunt.
- Minimum words. If one word works, do not use ten.
- No unsolicited explanations.
- No emoji unless asked.
1---
2name: security-api-security-hardener
3description: Durcissement de la sécurité des APIs — rate limiting, validation d'entrée, headers de sécurité, CORS, protection contre les attaques courantes. À utiliser quand l'utilisateur sécurise une API, configure des headers de sécurité ou implémente du rate limiting. Se déclenche aussi avec "sécurité API", "rate limiting", "headers sécurité", "CORS", "API hardening", "protection API", "OWASP API".
4metadata:
5 source: https://skillmd.com/skills/aibot88/security-api-security-hardener
6---
7
8# Durcissement de la Sécurité des APIs
9
10## Workflow
11
121. **Auditer** : identifier les failles potentielles (OWASP API Top 10).
132. **Configurer** : headers, CORS, rate limiting.
143. **Valider** : entrées, sorties, authentification.
154. **Monitorer** : logs de sécurité, détection d'anomalies.
16
17## OWASP API Top 10 — Checklist
18
19| # | Risque | Contrôle |
20|---|--------|----------|
21| 1 | Broken Object Level Authorization | Vérifier l'ownership sur chaque ressource |
22| 2 | Broken Authentication | JWT court, refresh rotation, MFA |
23| 3 | Broken Object Property Level Authorization | DTO de réponse, pas d'entités directes |
24| 4 | Unrestricted Resource Consumption | Rate limiting, pagination obligatoire |
25| 5 | Broken Function Level Authorization | RBAC sur chaque endpoint |
26| 6 | Unrestricted Access to Sensitive Business Flows | Captcha, anti-bot, limites métier |
27| 7 | Server Side Request Forgery | Whitelist d'URLs, pas d'URLs utilisateur |
28| 8 | Security Misconfiguration | Headers, CORS strict, erreurs génériques |
29| 9 | Improper Inventory Management | Documenter tous les endpoints, décommissionner les anciens |
30| 10 | Unsafe Consumption of APIs | Valider les réponses des APIs tierces |
31
32## Implémentation ASP.NET Core
33
34### Headers de sécurité
35
36```csharp
37app.Use(async (context, next) =>
38{
39 context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
40 context.Response.Headers.Append("X-Frame-Options", "DENY");
41 context.Response.Headers.Append("X-XSS-Protection", "0");
42 context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
43 context.Response.Headers.Append("Content-Security-Policy", "default-src 'self'");
44 context.Response.Headers.Append("Permissions-Policy", "camera=(), microphone=(), geolocation=()");
45 context.Response.Headers.Remove("Server");
46 context.Response.Headers.Remove("X-Powered-By");
47
48 await next();
49});
50```
51
52### Rate Limiting
53
54```csharp
55builder.Services.AddRateLimiter(options =>
56{
57 // Rate limit global
58 options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
59 RateLimitPartition.GetFixedWindowLimiter(
60 partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
61 factory: _ => new FixedWindowRateLimiterOptions
62 {
63 PermitLimit = 100,
64 Window = TimeSpan.FromMinutes(1)
65 }));
66
67 // Rate limit par endpoint
68 options.AddPolicy("strict", context =>
69 RateLimitPartition.GetSlidingWindowLimiter(
70 partitionKey: context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
71 factory: _ => new SlidingWindowRateLimiterOptions
72 {
73 PermitLimit = 10,
74 Window = TimeSpan.FromMinutes(1),
75 SegmentsPerWindow = 4
76 }));
77
78 options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
79});
80
81// Usage
82app.MapPost("/api/payments", handler).RequireRateLimiting("strict");
83```
84
85### Validation d'entrée
86
87```csharp
88public class CreatePaymentRequest
89{
90 [Required]
91 [Range(1, 99999999, ErrorMessage = "Le montant doit être entre 1 et 99999999 centimes")]
92 public int Amount { get; set; }
93
94 [Required]
95 [RegularExpression("^(EUR|USD|GBP)$")]
96 public string Currency { get; set; }
97
98 [Required]
99 [StringLength(100, MinimumLength = 1)]
100 public string RecipientId { get; set; }
101
102 [MaxLength(10)]
103 public Dictionary<string, string>? Metadata { get; set; }
104}
105```
106
107### CORS strict
108
109```csharp
110builder.Services.AddCors(options =>
111{
112 options.AddPolicy("Production", policy =>
113 {
114 policy.WithOrigins("https://app.company.com", "https://admin.company.com")
115 .WithMethods("GET", "POST", "PUT", "DELETE")
116 .WithHeaders("Authorization", "Content-Type")
117 .SetMaxAge(TimeSpan.FromHours(1));
118 });
119});
120```
121
122## Règles
123- Ne jamais exposer les entités de base de données directement — toujours des **DTOs**.
124- Les messages d'erreur ne doivent **jamais** révéler des détails d'implémentation.
125- Chaque endpoint doit vérifier l'**autorisation** (pas seulement l'authentification).
126- Le rate limiting doit être appliqué **avant** la logique métier.
127- Logger les tentatives d'accès non autorisées pour la détection d'intrusion.
128
129> Ce skill est un outil de sécurité défensif. Il aide à protéger les APIs contre les attaques courantes.
130
131
132## Communication Rules — MANDATORY
133
134- Ultra-concise. No filler, no preamble, no pleasantries.
135- Never say "happy to help", "sure!", "great question", "let me", or similar.
136- Tool first, talk second. Act before explaining.
137- Result first. Lead with outcome, not process.
138- Stop when done. No summary, no recap, no trailing commentary.
139- No politeness wrappers. Direct and blunt.
140- Minimum words. If one word works, do not use ten.
141- No unsolicited explanations.
142- No emoji unless asked.