Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 48

    API Protection Strategies

    Authentication alone does not stop abuse.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Define rate limits for /api/auth/** and /api/orders writes.
    2. Require X-Idempotency-Key on place-order and store processed keys.
    3. Configure CORS for known TechLearningPRO web origins only.
    4. Document gateway WAF rules alongside the Spring chain.

    Informative example

    CORS + idempotent place-order sketch.

    java
    @Bean
    SecurityFilterChain 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();
    }
    @Bean
    CorsConfigurationSource 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.

    3 questions
    1IntermediateQuestionDoes CORS protect your API from non-browser clients?+

    Answer

    No. CORS is enforced by browsers. Non-browser clients can still call the API; authz and rate limits still apply.
    2BeginnerQuestionWhy idempotency keys on POST place-order?+

    Answer

    Clients retry on timeouts; keys ensure at-most-once business effects for the same logical attempt.
    3IntermediateQuestionWhere should rate limits live?+

    Answer

    Preferably at the gateway/edge for volumetric attacks, with optional app-level limits per principal for fairness.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.