CS › Web-Network

HTTP method idempotency, CORS preflight, and Spring Security

How to distinguish safe and idempotent HTTP methods for retries, use Idempotency-Key on POST APIs, and configure CORS preflight cleanly in Spring Security 6.

HTTP method idempotency, CORS preflight, and Spring Security

Building reliable API retries requires a clear line between safe and idempotent HTTP methods, and connecting a browser frontend requires understanding how SOP and CORS preflight interact with Spring Security. This post covers both mechanisms under RFC 9110 and the Fetch Standard, along with Spring Security 6 configuration and common pitfalls.

Reference environment: RFC 9110 (HTTP Semantics), Fetch Standard (CORS), Spring Boot 3.x / Spring Security 6 / Kotlin 1.9

Safe vs. idempotent HTTP methods

RFC 9110 Section 9.2 defines two separate properties for HTTP methods:

  • Safe: The method is read-only and doesn’t modify server state.
  • Idempotent: Sending the exact same request once or N times leaves the server in the same final state.

A common misconception is that idempotent means “returns the same HTTP status code and body every time.” It doesn’t. Calling DELETE /api/orders/10 the first time might return 204 No Content, while a second call returns 404 Not Found. The response differs, but the server’s end state is identical—order 10 is gone—so DELETE is still idempotent.

MethodSafeIdempotentPractical API design note
GETYesYesRead-only; never trigger state mutations
HEADYesYesMetadata headers only, no response body
PUTNoYesReplaces the entire resource with the given payload
DELETENoYesRemoves the resource (404 on retry keeps the same state)
POSTNoNoCreates resources or triggers actions; retries can duplicate
PATCHNoNoPartial update; relative ops (+1000) break idempotency

Notice why PATCH isn’t idempotent by specification: a patch that sets status = "PAID" happens to be idempotent, while a patch that increments balance += 1000 isn’t. Unless you explicitly constrain a PATCH endpoint to absolute assignments, treat it as non-idempotent for retry logic.

Timeout retries and the Idempotency-Key pattern

When a client hits a ReadTimeout, it has no way of knowing whether the server dropped the request before processing or already committed the database transaction and lost the response on the way back. Retrying GET, PUT, or DELETE with exponential backoff is safe because repeating the operation won’t corrupt state. Blindly retrying a POST /api/payments call, however, can double-charge a customer.

To make POST endpoints safely retryable, I use the Idempotency-Key pattern. The client generates a unique UUID per logical action and sends it in a header:

1
2
3
4
5
curl -i -X POST https://api.example.com/api/payments \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <ACCESS_TOKEN>" \
  -H "Idempotency-Key: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d" \
  -d '{"orderId": "ORD-20240729-01", "amount": 25000}'

On the server, you record the key in a database table with a unique constraint (or Redis with atomic SET NX) alongside the request hash and final response:

  • Completed key: Skip the business logic and replay the stored response from the first execution.
  • In-flight key: Return 409 Conflict (or 425/429 depending on your contract) so concurrent duplicate clicks don’t race.
  • Same key, different payload: Reject with 422 Unprocessable Content to catch client bugs reusing old keys.
  • Expiration: Expire stored keys after 24 hours to 7 days so the idempotency table doesn’t grow unbounded.

When not to add Idempotency-Key: Don’t force idempotency keys onto naturally idempotent PUT/DELETE endpoints or read-only GET queries. Save the extra storage and coordination overhead for non-idempotent mutations where duplicate execution has real cost (payments, order creation, voucher issuance, external webhook dispatch).

Same-Origin Policy and CORS preflight mechanics

Browsers enforce the Same-Origin Policy (SOP), which treats two URLs as the same origin only when Scheme + Host + Port all match. By default, scripts on https://app.example.com can’t read responses from https://api.example.com. CORS (Cross-Origin Resource Sharing) lets the server opt in via response headers, using one of two browser flows:

  • Simple request: Uses GET, HEAD, or POST with only CORS-safelisted headers and a Content-Type of application/x-www-form-urlencoded, multipart/form-data, or text/plain. The browser sends the request directly without a preflight check.
  • Preflight request: Triggered by most modern REST APIs—anything using application/json, an Authorization header, custom headers like Idempotency-Key, or PUT/DELETE methods. Before sending the real request, the browser sends an OPTIONS preflight to ask the server for permission.
sequenceDiagram
    participant Browser as Browser
    participant Security as Spring Security
    participant API as API Controller

    Browser->>Security: OPTIONS /api/orders + Origin
    Security-->>Browser: 200 OK + Allow-Origin, Max-Age

    Note over Browser,Security: Preflight passed; send actual request
    Browser->>Security: POST /api/orders + Authorization
    Security->>API: Forward after auth
    API-->>Browser: 201 Created + Allow-Origin

Because every uncached preflight adds an extra round trip, return Access-Control-Max-Age so the browser caches the preflight result. Keep in mind that browsers cap this value regardless of what you send (Chromium caps it at 7,200 seconds / 2 hours, Firefox at 86,400 seconds / 24 hours).

Configuring CORS in Spring Security 6

A classic Spring Boot bug happens when you only configure @CrossOrigin or WebMvcConfigurer.addCorsMappings() on an app that uses Spring Security. The browser’s OPTIONS preflight arrives without an Authorization header or session cookie, and SecurityFilterChain blocks it with 401 or 403 before the request ever reaches DispatcherServlet.

Enabling http.cors {} with a CorsConfigurationSource bean puts Spring’s CorsFilter ahead of the authentication and authorization filters, letting DefaultCorsProcessor answer preflight requests first.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// src/main/kotlin/com/example/security/SecurityConfig.kt
package com.example.security

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.web.SecurityFilterChain
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.UrlBasedCorsConfigurationSource

@Configuration
@EnableWebSecurity
class SecurityConfig {

    @Bean
    fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
        http
            .cors { it.configurationSource(corsConfigurationSource()) }
            .csrf { it.disable() } // Stateless Bearer-token API only
            .authorizeHttpRequests { auth ->
                auth.requestMatchers("/api/public/**").permitAll()
                    .anyRequest().authenticated()
            }
        return http.build()
    }

    @Bean
    fun corsConfigurationSource(): CorsConfigurationSource {
        val config = CorsConfiguration().apply {
            allowedOrigins = listOf("https://app.example.com")
            allowedMethods = listOf("GET", "POST", "PUT", "DELETE", "OPTIONS")
            allowedHeaders = listOf("Authorization", "Content-Type", "Idempotency-Key")
            allowCredentials = true
            maxAge = 3600L
        }
        return UrlBasedCorsConfigurationSource().apply {
            registerCorsConfiguration("/api/**", config)
        }
    }
}

I verify the preflight response directly from the terminal with curl before testing in a browser:

1
2
3
4
curl -i -X OPTIONS http://localhost:8080/api/orders \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: Authorization, Content-Type, Idempotency-Key"

Common CORS security pitfalls and checklist

Warning: CORS is a browser enforcement mechanism, not a server firewall. curl, Postman, and server-to-server HTTP clients ignore CORS headers completely. Never treat CORS as a substitute for authentication, authorization, or CSRF protection.

  1. Combining Access-Control-Allow-Origin: * with Allow-Credentials: true: The Fetch Standard explicitly forbids wildcard origins on credentialed requests, and browsers block the response immediately. List exact origins in allowedOrigins (or use allowedOriginPatterns so Spring echoes the matched Origin).
  2. Assuming CORS blocks CSRF on cookie-based sessions: Simple POST requests (such as form submissions) reach your server without a preflight check. If your API relies on session cookies, enforce SameSite cookie attributes and CSRF token validation.
  3. Duplicate CORS headers from a reverse proxy and the backend: If both Nginx and Spring Boot append Access-Control-Allow-Origin, the duplicated header causes browsers to reject the response. Own CORS headers in one layer only—either the API gateway or the application.

Idempotency and CORS checklist

  • Restrict automatic client retries to idempotent methods (GET, PUT, DELETE) or POST endpoints protected by Idempotency-Key.
  • Validate payload consistency and set a bounded TTL on stored idempotency keys.
  • Wire CORS through SecurityFilterChain (http.cors {}) so preflight OPTIONS requests aren’t blocked by auth filters.
  • Avoid * with allowCredentials = true, and add Idempotency-Key to allowedHeaders when browsers send it.
  • Emit CORS headers from a single layer (gateway or backend, never both).

References

This post is licensed under CC BY 4.0 by the author.