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.
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.
| Method | Safe | Idempotent | Practical API design note |
|---|---|---|---|
GET | Yes | Yes | Read-only; never trigger state mutations |
HEAD | Yes | Yes | Metadata headers only, no response body |
PUT | No | Yes | Replaces the entire resource with the given payload |
DELETE | No | Yes | Removes the resource (404 on retry keeps the same state) |
POST | No | No | Creates resources or triggers actions; retries can duplicate |
PATCH | No | No | Partial 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(or425/429depending on your contract) so concurrent duplicate clicks don’t race. - Same key, different payload: Reject with
422 Unprocessable Contentto 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, orPOSTwith only CORS-safelisted headers and aContent-Typeofapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain. The browser sends the request directly without a preflight check. - Preflight request: Triggered by most modern REST APIs—anything using
application/json, anAuthorizationheader, custom headers likeIdempotency-Key, orPUT/DELETEmethods. Before sending the real request, the browser sends anOPTIONSpreflight 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.
- Combining
Access-Control-Allow-Origin: *withAllow-Credentials: true: The Fetch Standard explicitly forbids wildcard origins on credentialed requests, and browsers block the response immediately. List exact origins inallowedOrigins(or useallowedOriginPatternsso Spring echoes the matchedOrigin). - Assuming CORS blocks CSRF on cookie-based sessions: Simple
POSTrequests (such as form submissions) reach your server without a preflight check. If your API relies on session cookies, enforceSameSitecookie attributes and CSRF token validation. - 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) orPOSTendpoints protected byIdempotency-Key. - Validate payload consistency and set a bounded TTL on stored idempotency keys.
- Wire CORS through
SecurityFilterChain(http.cors {}) so preflightOPTIONSrequests aren’t blocked by auth filters. - Avoid
*withallowCredentials = true, and addIdempotency-KeytoallowedHeaderswhen browsers send it. - Emit CORS headers from a single layer (gateway or backend, never both).