API Protection Strategies
Authentication alone does not stop abuse.
Introduction
Authentication alone does not stop abuse. Production Orders APIs need rate limiting, idempotency, tight CORS, quotas, and often a WAF or API gateway in front of Spring Boot.
Protection is defense in depth: gateway rules catch volumetric abuse; the app enforces idempotency keys on payment/place-order; CORS prevents drive-by browser calls from unknown origins; partner HMAC signing proves B2B requests.
Design these controls with distinct purposes — do not pretend rate limits replace authorization, or that CORS is an auth mechanism.
Keep secrets and signing keys in secret stores. Examples use placeholders only.
Purpose of this lesson
Layer rate limits, idempotency, CORS, and gateway controls to protect Orders APIs from abuse and replay.
Understanding the topic
Each control stops a different failure mode.
- Rate limiting: per IP and per principal token buckets.
- Idempotency keys: safe retries on place-order without double charge.
- CORS: browser origin allow-list — not a substitute for auth.
- Quotas: per-tenant daily caps at gateway or app.
- WAF / bot controls: block obvious scrapers before the JVM.
Step-by-step explanation
- Define rate limits for
/api/auth/**and/api/orderswrites. - Require
X-Idempotency-Keyon place-order and store processed keys. - Configure CORS for known TechLearningPRO web origins only.
- Document gateway WAF rules alongside the Spring chain.
Informative example
CORS + idempotent place-order sketch.
@BeanSecurityFilterChain api(HttpSecurity http) throws Exception {return http.cors(Customizer.withDefaults()).csrf(csrf -> csrf.disable()).sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll().anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build();}@BeanCorsConfigurationSource corsConfigurationSource() {CorsConfiguration config = new CorsConfiguration();config.setAllowedOrigins(List.of("https://app.techlearningpro.example"));config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));config.setAllowedHeaders(List.of("Authorization", "Content-Type", "X-Idempotency-Key"));config.setAllowCredentials(true);UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();source.registerCorsConfiguration("/api/**", config);return source;}// OrderService.place(customerId, idempotencyKey, cmd) — dedupe by key
Real-world use
During a flash sale, TechLearningPRO saw duplicate place-order retries from flaky mobile networks and a scrape storm on catalog endpoints. Idempotency keys saved payments from double capture; gateway rate limits kept the JVM from melting; CORS stayed tight so random websites could not fire credentialed browser calls.
Security implications
Abuse protection preserves availability and integrity.
- Replay without idempotency can double-charge.
- Open CORS + cookies is a data-leak pattern.
- Partner HMAC keys rotate on a schedule; use
${PARTNER_HMAC_KEY}placeholders.
Best practices
- Put volumetric defenses at the edge; keep business idempotency in the service.
- Separate auth rate limits from general API limits.
- Monitor 429s and idempotency conflicts as product signals.
Common mistakes
- Using
allowedOrigins('*')together with credentials. - Treating CORS as authentication.
- Rate-limiting only in-app while the app is already CPU-starved — prefer gateway limits first.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1IntermediateQuestionDoes CORS protect your API from non-browser clients?+
Answer
2BeginnerQuestionWhy idempotency keys on POST place-order?+
Answer
3IntermediateQuestionWhere should rate limits live?+
Answer
Hands-on exercise
Lab. Add idempotency on place-order and send the same key twice; assert one order. Then configure CORS for a single origin and confirm a disallowed origin fails the browser preflight (or Spring rejects).
Summary
API protection strategies complete the Orders security module: identity, access, tokens, and abuse defenses working together.