Implementing API Security

1. Implementing Input Sanitization

ThreatMitigation
SQL injectionParameterized queries / ORM binds
XSSOutput encoding; CSP; HTML sanitizer for rich text
XXEDisable external entities in XML parser
SSRFURL allow-list; block private IP ranges
Path traversalCanonical path + base dir check
LDAP injectionEscape 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

HeaderPurpose
Strict-Transport-SecurityForce HTTPS
Content-Security-PolicyXSS defense
X-Content-Type-Options: nosniffPrevent MIME sniff
X-Frame-Options: DENYClickjacking
Referrer-Policy: no-referrerPrivacy
Permissions-PolicyDisable 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

PracticeDetail
CIDR rangesUse IP CIDR matcher
Trust proxyRead X-Forwarded-For only when behind trusted LB
Per-key allowlistRestrict API key by source
Default denyExplicit allow only

6. Implementing Audit Logging

EventLog
Auth success/failureUser, IP, method
Privileged actionAdmin operations
Data exportBulk read events
Config changeBefore/after values
Permission changeGrants/revokes

7. Implementing Sensitive Data Handling

PracticeDetail
Encryption at restField-level for PII; KMS-managed keys
Encryption in transitTLS 1.2+ everywhere
TokenizationReplace card numbers with tokens
Masking in logsLast 4 of card; redact emails
Data minimizationDon't collect what you don't need

8. Implementing API Key Validation

StepDetail
Read headerX-API-Key or Authorization: ApiKey ...
Hash + lookupSHA-256 then DB query
Check statusActive, not revoked, not expired
Constant-time compareAvoid timing leaks
CacheShort TTL on validated keys

9. Implementing Request/Response Encryption

LayerDetail
TransportTLS handles 99% of cases
Payload (JWE)End-to-end across intermediaries
Field-levelEncrypt sensitive fields independently

10. Implementing Security Filters

OrderFilter
1Correlation ID
2Rate limit
3CORS
4CSRF (web sessions)
5Auth (JWT/session)
6Authorization
7Audit log

11. Implementing CSRF Protection

StrategyDetail
Synchronizer tokenPer-session token in form / header
Double-submit cookieToken in cookie + header, must match
SameSite=StrictSufficient for many cases
Stateless (JWT in header)Not vulnerable; cookies are

12. Implementing Rate Limiting for Security

Endpoint TypeLimit
Login5/min/IP + 5/min/user
Password reset3/hour/email
API (per key)1000/min
Public60/min/IP