Implementing API Security
1. Implementing Input Sanitization
| Threat | Mitigation |
|---|---|
| SQL injection | Parameterized queries / ORM binds |
| XSS | Output encoding; CSP; HTML sanitizer for rich text |
| XXE | Disable external entities in XML parser |
| SSRF | URL allow-list; block private IP ranges |
| Path traversal | Canonical path + base dir check |
| LDAP injection | Escape or use parameterized search |
2. Implementing CORS Configuration
Example: Spring CORS
@Bean
CorsConfigurationSource corsConfig() {
var c = new CorsConfiguration();
c.setAllowedOrigins(List.of("https://app.acme.com"));
c.setAllowedMethods(List.of("GET","POST","PUT","DELETE","PATCH"));
c.setAllowedHeaders(List.of("Authorization","Content-Type","X-Correlation-Id"));
c.setExposedHeaders(List.of("X-Correlation-Id"));
c.setAllowCredentials(true);
c.setMaxAge(3600L);
var src = new UrlBasedCorsConfigurationSource();
src.registerCorsConfiguration("/**", c);
return src;
}
Warning: Never use
* for origins when allowCredentials=true.3. Implementing Security Headers
| Header | Purpose |
|---|---|
| Strict-Transport-Security | Force HTTPS |
| Content-Security-Policy | XSS defense |
| X-Content-Type-Options: nosniff | Prevent MIME sniff |
| X-Frame-Options: DENY | Clickjacking |
| Referrer-Policy: no-referrer | Privacy |
| Permissions-Policy | Disable unused browser features |
4. Implementing Request Signing Validation
Example: HMAC signature
String stringToSign = method + "\n" + path + "\n" + timestamp + "\n" + sha256(body);
String expected = base64(hmacSha256(secret, stringToSign));
if (!MessageDigest.isEqual(expected.getBytes(), provided.getBytes()))
throw new UnauthorizedException("bad signature");
if (Math.abs(now - timestamp) > 300_000) throw new UnauthorizedException("stale");
5. Implementing IP Whitelisting Logic
| Practice | Detail |
|---|---|
| CIDR ranges | Use IP CIDR matcher |
| Trust proxy | Read X-Forwarded-For only when behind trusted LB |
| Per-key allowlist | Restrict API key by source |
| Default deny | Explicit allow only |
6. Implementing Audit Logging
| Event | Log |
|---|---|
| Auth success/failure | User, IP, method |
| Privileged action | Admin operations |
| Data export | Bulk read events |
| Config change | Before/after values |
| Permission change | Grants/revokes |
7. Implementing Sensitive Data Handling
| Practice | Detail |
|---|---|
| Encryption at rest | Field-level for PII; KMS-managed keys |
| Encryption in transit | TLS 1.2+ everywhere |
| Tokenization | Replace card numbers with tokens |
| Masking in logs | Last 4 of card; redact emails |
| Data minimization | Don't collect what you don't need |
8. Implementing API Key Validation
| Step | Detail |
|---|---|
| Read header | X-API-Key or Authorization: ApiKey ... |
| Hash + lookup | SHA-256 then DB query |
| Check status | Active, not revoked, not expired |
| Constant-time compare | Avoid timing leaks |
| Cache | Short TTL on validated keys |
9. Implementing Request/Response Encryption
| Layer | Detail |
|---|---|
| Transport | TLS handles 99% of cases |
| Payload (JWE) | End-to-end across intermediaries |
| Field-level | Encrypt sensitive fields independently |
10. Implementing Security Filters
| Order | Filter |
|---|---|
| 1 | Correlation ID |
| 2 | Rate limit |
| 3 | CORS |
| 4 | CSRF (web sessions) |
| 5 | Auth (JWT/session) |
| 6 | Authorization |
| 7 | Audit log |
11. Implementing CSRF Protection
| Strategy | Detail |
|---|---|
| Synchronizer token | Per-session token in form / header |
| Double-submit cookie | Token in cookie + header, must match |
| SameSite=Strict | Sufficient for many cases |
| Stateless (JWT in header) | Not vulnerable; cookies are |
12. Implementing Rate Limiting for Security
| Endpoint Type | Limit |
|---|---|
| Login | 5/min/IP + 5/min/user |
| Password reset | 3/hour/email |
| API (per key) | 1000/min |
| Public | 60/min/IP |