Playbook: CORS failures
Diagnose browser CORS errors by replaying the preflight request yourself, finding which layer (API Gateway, CloudFront, ASP.NET Core) should answer it, and fixing credentials, header and error-response gaps without opening the API to every origin.
Assumes: .NET 10 LTS · ASP.NET Core 10 · AWS CLI v2 · API Gateway REST and HTTP APIs · Region us-east-1. Verified against official sources on 2026-11-18.
Learning objectives
By the end of this playbook you can:
- Explain in two sentences why CORS is a browser rule and why
curlworking proves nothing about it. - Tell a simple request from a preflighted request, and say which headers the browser sends and expects back.
- Decide which layer should answer the preflight: API Gateway, CloudFront, the ALB's application, or ASP.NET Core, and avoid configuring two.
- Recognise the five classic causes: missing origin, missing header allowance, credentials with a wildcard, preflight blocked by an authorizer, and error responses without CORS headers.
- Replay a preflight with a C# tool that applies the browser's rules and prints a verdict.
- Fix the configuration without resorting to "allow every origin".
Prerequisites
- Request validation, models, versioning and CORS, which explains the mechanism and the configuration in each product; this playbook is the diagnosis method
- API Gateway: REST, HTTP and WebSocket and Lambda authorizers
- ASP.NET Core API baseline
- Tools: a browser with developer tools, AWS CLI v2, .NET 10 SDK
Why this matters in banking
The new Harbourline web banking front end, served from https://app.harbourline.example, calls the API at https://api.harbourline.example. On release day every call fails in the browser with "blocked by CORS policy", while the mobile app and the partner integration work perfectly. A developer under time pressure changes the API to reply Access-Control-Allow-Origin: * and reflects any Origin header back with credentials allowed. The screen works. A security review a week later finds that any website a customer visits can now call the banking API with the customer's session and read the answers.
CORS errors are therefore two problems in one: a genuine availability problem (the front end cannot work) and a tempting security regression (the quick fix). The playbook's job is to give you a fix that is both correct and narrow.
The idea in plain language
A browser lets a page load from one origin (scheme, host and port together) but, by default, forbids that page's JavaScript from reading responses from a different origin. CORS (Cross-Origin Resource Sharing) is the server's way of saying "pages from this origin may read my responses".
Three details explain nearly every incident:
- It is the browser that blocks, not the server. The server usually received and processed the request. The browser then refuses to give the response to your script. That is why a state-changing call can succeed on the server while the front end shows an error.
- Some requests are preceded by a preflight. If the request uses a method other than GET, HEAD or POST, a content type other than the simple ones (so
application/jsontriggers it), or custom headers such asAuthorization, the browser first sends anOPTIONSrequest asking permission. Only if the answer is right does it send the real request. - The preflight does not carry your credentials. The
Authorizationheader and cookies are not sent on the preflight. An authorizer that demands a token on every request, includingOPTIONS, blocks the preflight, and the browser reports it as a CORS error.
Analogy: A visitor from another branch (the page) asks the front desk (the browser) to fetch a file from your branch (the API). The desk first phones your branch: "Will you hand files to staff from the High Street branch, with this kind of request?" That phone call is the preflight. If your switchboard demands a staff badge number from the caller before even answering, the desk hears silence and refuses the visitor, even though your branch would have said yes.
What the browser sends and expects
| Step | Browser sends | Server must answer with |
|---|---|---|
| Preflight | OPTIONS /v1/payments, header Origin: https://app.harbourline.example, Access-Control-Request-Method: POST, Access-Control-Request-Headers: authorization,content-type | A 2xx status and Access-Control-Allow-Origin matching the origin, Access-Control-Allow-Methods including POST, Access-Control-Allow-Headers including each requested header. Optionally Access-Control-Max-Age |
| Actual request | The real call with Origin | Access-Control-Allow-Origin again on the real response, including error responses |
With credentials (cookies or fetch with credentials: "include") | As above | Access-Control-Allow-Credentials: true and an exact origin. A wildcard * is not allowed with credentials |
What problem the AWS services solve
AWS does not decide your CORS policy, but the layer you configure matters, because several layers can add (or forget) the headers:
- API Gateway HTTP API: has a built-in CORS setting. When configured, API Gateway answers preflight requests itself, before your authorizer or backend sees them.
- API Gateway REST API: you must provide an
OPTIONSmethod (often a mock integration) for the preflight and make your backend or integration responses carryAccess-Control-Allow-Origin. The built-in gateway error responses (such as 401, 403, 429 and 5xx) do not include CORS headers unless you configure them. - CloudFront: can add CORS headers with a response headers policy, but must forward the
Originheader or include it in the cache key; otherwise a cached response for one origin is served to another. - ALB: has no CORS feature. The application behind it (ASP.NET Core) answers.
- ASP.NET Core: has CORS middleware. Order matters.
The sharp edge is duplicate configuration. If API Gateway adds Access-Control-Allow-Origin and ASP.NET Core adds it too, the browser sees two values and rejects the response. Choose one layer to own CORS for each path.
Microsoft / Azure comparison
| You know (Microsoft/Azure) | AWS equivalent | What's different |
|---|---|---|
app.UseCors() in ASP.NET Core | The same, if the app owns CORS | Unchanged. Put UseCors after UseRouting and before UseAuthentication and UseAuthorization |
| App Service CORS setting in the portal | API Gateway CORS setting (HTTP API) or the OPTIONS method (REST API) | There is no single platform switch. Where you configure it depends on the API type |
APIM cors policy | HTTP API CORS configuration | HTTP APIs answer the preflight before authentication. REST APIs need explicit wiring |
| Azure Front Door rules engine adding response headers | CloudFront response headers policy | Remember the cache and Origin forwarding issue |
| Azure Static Web Apps managed API with same origin | CloudFront serving both / and /api/* under one domain | Same origin means no CORS at all. This is often the cleanest fix |
| Browser developer tools "CORS error" | Same | The console message rarely tells you if the real failure was a 401, 403 or 500 |
Architecture
Who must answer, and where it goes wrong
The first-five-minutes decision tree
Step-by-step implementation
Minutes 0 to 5: confirm it is a CORS problem and find the real request
- Open the browser's Network tab, reproduce the failure, and filter by the API host. Note whether there is an
OPTIONSrequest and what the real request status is. - Read the exact console message. "No 'Access-Control-Allow-Origin' header is present" means missing header on the response in question. "The value of the 'Access-Control-Allow-Origin' header must not be the wildcard when the credentials mode is include" is the credentials rule. "Request header field authorization is not allowed" means the preflight did not list that header.
- Check the real status code. If the real call returned 401, 403, 429 or 5xx without CORS headers, the browser shows a CORS error but the true failure is an auth or server error. Fix that first.
Minutes 5 to 15: replay the preflight outside the browser
Use the C# probe below (or curl -i -X OPTIONS with the three headers). Replaying it from a terminal shows exactly what the server returned for the same preflight, without the browser's filtering. It works because the preflight is just an HTTP request. What the terminal cannot show you is the browser's decision, so the probe applies the same rules.
Minutes 15 to 30: find the layer that answered
Look at response headers on the preflight: x-amzn-requestid or apigw-requestid shows API Gateway answered, x-amz-cf-id shows CloudFront was in the path, the Server: Kestrel header (if you expose it) shows the app. Then check the configuration of that layer (see the console and CLI sections). Check for a second layer adding headers.
Minutes 30 to 45: apply the narrowest fix
| Finding | Fix |
|---|---|
| Origin not in the allowed list | Add the exact origin (scheme, host, port) to the configured list. Do not use * for an authenticated API |
| Authorization or content-type not allowed | Add them to AllowHeaders |
| Method (PUT, DELETE, PATCH) not allowed | Add it to AllowMethods |
| Wildcard with credentials | Use a specific origin and Access-Control-Allow-Credentials: true, or stop using cookies cross-origin |
| Authorizer blocks OPTIONS | Remove the authorizer from OPTIONS, or use an HTTP API with built-in CORS |
| Error responses lack headers | REST API: add CORS headers to the gateway responses for 4XX and 5XX. ASP.NET Core: make sure the exception handler runs after UseCors |
| Two layers add headers | Keep one layer |
| CloudFront caches the wrong origin's headers | Forward or cache by Origin, or answer CORS at the origin and add Vary: Origin |
Minutes 45 to 60: prevent recurrence
Add an automated CORS test in the deployment pipeline that replays a preflight against the environment's own front-end origin, and a negative test that a hostile origin gets no allow header. Record the decision on which layer owns CORS and the approved list of origins per environment.
AWS Console instructions
- Console → API Gateway → (HTTP API) → CORS: shows allowed origins, methods, headers, expose headers, max age and the credentials flag.
- Console → API Gateway → (REST API) → Resources → (path) → OPTIONS: check the method exists, has a mock integration and an integration response with the three headers. Then Gateway responses: check the Default 4XX and Default 5XX responses include
Access-Control-Allow-Origin. - Console → API Gateway → (REST API) → Resources → OPTIONS → Method request: authorization should be None for the preflight.
- Console → CloudFront → Distributions → (distribution) → Behaviors → Edit: check the response headers policy, the origin request policy (does it forward
Origin?) and the cache policy. - Console → CloudWatch → Logs: the API Gateway access log group, to confirm the OPTIONS request arrived and what status was returned.
AWS CLI
# 1. Replay a preflight exactly as a browser would, and show the response headers.
curl -i -X OPTIONS "https://api.harbourline.example/v1/payments" \
-H "Origin: https://app.harbourline.example" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: authorization,content-type"
# 2. Negative test: a hostile origin must NOT receive an allow-origin header.
curl -i -X OPTIONS "https://api.harbourline.example/v1/payments" \
-H "Origin: https://evil.example" \
-H "Access-Control-Request-Method: POST"
# 3. HTTP API: read the CORS configuration.
aws apigatewayv2 get-api --api-id a1b2c3d4e5 \
--query 'CorsConfiguration' --profile learn-sandbox
# 4. HTTP API: set a narrow CORS configuration (specific origin, needed headers only).
aws apigatewayv2 update-api --api-id a1b2c3d4e5 \
--cors-configuration '{"AllowOrigins":["https://app.harbourline.example"],"AllowMethods":["GET","POST"],"AllowHeaders":["authorization","content-type"],"MaxAge":600,"AllowCredentials":false}' \
--profile learn-sandbox
# 5. REST API: list gateway responses to see whether the 4XX/5XX defaults carry CORS headers.
aws apigateway get-gateway-responses --rest-api-id a1b2c3d4e5 \
--query 'items[?responseType==`DEFAULT_4XX` || responseType==`DEFAULT_5XX`].[responseType,responseParameters]' \
--profile learn-sandboxThe addresses and names are fictional (.example domains are reserved for documentation).
Infrastructure as Code
using Amazon.CDK;
using Amazon.CDK.AWS.Apigatewayv2;
using Constructs;
public class WebApiCorsStack : Stack
{
public WebApiCorsStack(Construct scope, string id, IStackProps props) : base(scope, id, props)
{
// HTTP API with a narrow, explicit CORS policy. API Gateway answers the preflight itself.
var api = new CfnApi(this, "BankingHttpApi", new CfnApiProps
{
Name = "hl-banking-http",
ProtocolType = "HTTP",
CorsConfiguration = new CfnApi.CorsProperty
{
AllowOrigins = new[] { "https://app.harbourline.example" },
AllowMethods = new[] { "GET", "POST", "PUT", "DELETE" },
AllowHeaders = new[] { "authorization", "content-type", "idempotency-key" },
ExposeHeaders = new[] { "x-correlation-id" },
AllowCredentials = false,
MaxAge = 600
}
});
Amazon.CDK.Tags.Of(this).Add("Project", "cea-lab");
Amazon.CDK.Tags.Of(this).Add("Lab", "m17-playbook-cors");
}
}Complete code
A preflight probe that applies the browser's rules
This console tool sends a preflight OPTIONS request and then checks the answer the way a browser would, printing a verdict for each rule. The evaluation lives in a pure method so you can unit test it.
using System.Net.Http.Headers;
if (args.Length < 2)
{
Console.WriteLine("usage: CorsProbe <url> <origin> [method=POST] [headers=authorization,content-type] [credentials=false]");
return 1;
}
var url = args[0];
var origin = args[1];
var method = args.Length > 2 ? args[2] : "POST";
var requestHeaders = args.Length > 3 ? args[3] : "authorization,content-type";
var withCredentials = args.Length > 4 && bool.Parse(args[4]);
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
using var request = new HttpRequestMessage(HttpMethod.Options, url);
request.Headers.TryAddWithoutValidation("Origin", origin);
request.Headers.TryAddWithoutValidation("Access-Control-Request-Method", method);
request.Headers.TryAddWithoutValidation("Access-Control-Request-Headers", requestHeaders);
using var response = await http.SendAsync(request);
var seen = response.Headers.Concat(response.Content.Headers)
.ToDictionary(h => h.Key, h => h.Value.ToArray(), StringComparer.OrdinalIgnoreCase);
Console.WriteLine($"Preflight status: {(int)response.StatusCode}");
foreach (var (name, values) in seen.Where(h => h.Key.StartsWith("access-control", StringComparison.OrdinalIgnoreCase) || h.Key.Equals("vary", StringComparison.OrdinalIgnoreCase)))
Console.WriteLine($" {name}: {string.Join(" | ", values)}");
var problems = CorsRules.Evaluate((int)response.StatusCode, seen, origin, method, requestHeaders, withCredentials);
if (problems.Count == 0) { Console.WriteLine("VERDICT: a browser would accept this preflight."); return 0; }
Console.WriteLine("VERDICT: a browser would BLOCK this request:");
foreach (var p in problems) Console.WriteLine($" - {p}");
return 2;
public static class CorsRules
{
public static List<string> Evaluate(
int status,
IReadOnlyDictionary<string, string[]> headers,
string origin, string method, string requestHeaders, bool withCredentials)
{
var problems = new List<string>();
if (status is < 200 or > 299)
problems.Add($"Preflight returned {status}; it must be a 2xx. Check authorizers, missing OPTIONS route, WAF.");
string[] Get(string name) => headers.TryGetValue(name, out var v) ? v : Array.Empty<string>();
var allowOrigin = Get("Access-Control-Allow-Origin");
if (allowOrigin.Length == 0)
problems.Add("No Access-Control-Allow-Origin header. The layer answering OPTIONS has no matching origin.");
else if (allowOrigin.Length > 1 || allowOrigin[0].Contains(','))
problems.Add("Access-Control-Allow-Origin appears more than once. Two layers are adding it.");
else if (allowOrigin[0] != "*" && !string.Equals(allowOrigin[0], origin, StringComparison.Ordinal))
problems.Add($"Allow-Origin is '{allowOrigin[0]}' but the request origin is '{origin}'.");
else if (allowOrigin[0] == "*" && withCredentials)
problems.Add("Allow-Origin is '*' but credentials are included: browsers reject this.");
if (withCredentials && !string.Equals(Get("Access-Control-Allow-Credentials").FirstOrDefault(), "true", StringComparison.OrdinalIgnoreCase))
problems.Add("Credentials are used but Access-Control-Allow-Credentials is not 'true'.");
var allowMethods = Split(Get("Access-Control-Allow-Methods"));
if (!IsSimpleMethod(method) && !allowMethods.Contains(method, StringComparer.OrdinalIgnoreCase) && !allowMethods.Contains("*"))
problems.Add($"Method {method} is not listed in Access-Control-Allow-Methods.");
var allowHeaders = Split(Get("Access-Control-Allow-Headers"));
foreach (var h in Split(new[] { requestHeaders }))
{
if (!allowHeaders.Contains(h, StringComparer.OrdinalIgnoreCase) && !(allowHeaders.Contains("*") && !withCredentials))
problems.Add($"Request header '{h}' is not listed in Access-Control-Allow-Headers.");
}
return problems;
}
static bool IsSimpleMethod(string m) => m.ToUpperInvariant() is "GET" or "HEAD" or "POST";
static string[] Split(IEnumerable<string> values) =>
values.SelectMany(v => v.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)).ToArray();
}Run it with dotnet run -- https://api.harbourline.example/v1/payments https://app.harbourline.example POST authorization,content-type. The project is a default console project targeting net10.0. For a free local test, run any ASP.NET Core app from the next listing on http://localhost:5080 and point the probe at it.
ASP.NET Core CORS with the right middleware order
var builder = WebApplication.CreateBuilder(args);
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
builder.Services.AddCors(options =>
{
options.AddPolicy("web-banking", policy => policy
.WithOrigins(allowedOrigins) // exact origins, never "*" for an authenticated API
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("authorization", "content-type", "idempotency-key")
.WithExposedHeaders("x-correlation-id")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10)));
});
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseExceptionHandler(e => e.Run(async ctx =>
{
ctx.Response.StatusCode = 500;
await ctx.Response.WriteAsJsonAsync(new { error = "internal_error" });
}));
app.UseRouting();
app.UseCors("web-banking"); // after UseRouting, BEFORE authentication and authorization
app.UseAuthentication();
app.UseAuthorization();
app.MapGet("/v1/accounts", () => Results.Ok(new[] { "ACC-1001" })).RequireAuthorization();
app.Run();{
"Cors": {
"AllowedOrigins": [ "https://app.harbourline.example", "http://localhost:5173" ]
}
}Code explained line by line
- The probe sets the three request headers a real preflight carries:
Origin,Access-Control-Request-MethodandAccess-Control-Request-Headers. The server's answer to those exact headers is what the browser judges. response.Headers.Concat(response.Content.Headers)merges both header collections, because .NET splits headers between the response and the content, and the CORS headers can appear in either.CorsRules.Evaluateis static and takes plain values, so a unit test can pass a fake header dictionary and assert the list of problems without any network.- The rule "Allow-Origin appears more than once" catches the duplicate-layer bug: the header collection holds two values, or one comma-joined value.
- The credentials rules encode the two facts people forget: the wildcard is rejected when credentials are included, and
Access-Control-Allow-Credentialsmust be exactlytrue. IsSimpleMethodskips the method check for GET, HEAD and POST because those are allowed without a listing (the headers check still applies to custom headers).- In ASP.NET Core,
UseCorsgoes afterUseRoutingand before authentication and authorization, so a preflight is answered before it can be rejected for a missing token. - The origins come from configuration, so each environment has its own exact list and nothing is hard-coded to a wildcard.
UseExceptionHandlercomes first so unhandled errors become a controlled 500. Because the exception handler runs in the pipeline aboveUseCors, a response produced there may lack CORS headers, which is another source of "CORS error" for what is really a 500. Test it, and if needed apply the CORS policy to the error path as well.
Security considerations
⚠ Learning shortcut — not for production
Local development often uses AllowAnyOrigin() or a wildcard to get a front end working. The same code reaching production lets every website talk to the API from a customer's browser. Use an explicit origin list per environment, kept in configuration, and add a test that a hostile origin gets no allow header.
- CORS is not authentication. It stops a browser page from reading responses. It does not stop
curl, a partner server or an attacker's script outside a browser. The API must still authenticate and authorise every request. - Never reflect the
Originheader blindly with credentials allowed. That reproduces "any site can use the user's session". - Prefer bearer tokens in headers over cookies for cross-origin calls, which sidesteps most credentials complications and reduces CSRF exposure. If cookies are required, use exact origins,
SameSitesettings and CSRF protection. - List only the headers and methods you need. A broad
AllowHeadersof*hides intent. - Same origin is safest. Serving the front end and
/api/*from one CloudFront domain removes CORS from the design. Weigh that against caching and deployment independence. - Review
nullandlocalhostorigins. Remove development origins from production configuration. - Security review sign-off on the origin list is part of release approval; this lesson does not replace it.
Banking use case
For Harbourline's web front end, the team chooses an HTTP API with a narrow CORS block (one origin per environment, three headers, no credentials, bearer token in Authorization). The preflight is answered by API Gateway, so the JWT authorizer never sees OPTIONS. A pipeline test replays a preflight from the production origin and from a hostile origin and fails the release if the second one receives an allow header. A separate legacy REST API for statements gets gateway-response CORS headers for 4XX and 5XX so a 401 shows up in the browser as a 401, not as a misleading CORS error. The incident record states which layer owns CORS and who approved the origin list.
Common mistakes
- Fixing with
*and credentials. Browsers reject that combination, and the "fix" of reflecting the origin opens the API. - Blaming CORS when the real error is 401, 403 or 500. Always read the real response status.
- Configuring CORS in two layers. Duplicated
Access-Control-Allow-Originvalues break the response. - An authorizer on the OPTIONS route. The preflight has no token.
- Forgetting
idempotency-keyor a custom header inAllowHeaders, so only the calls that send it fail. UseCorsin the wrong place in the ASP.NET Core pipeline.- CloudFront cache serves the wrong CORS headers because
Originis not part of the cache key. - Testing only with
curl, which never enforces CORS.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| "No 'Access-Control-Allow-Origin' header is present" on a POST | Preflight passed but the real response lacks the header | Add the header on real responses (backend or integration response) |
| Preflight returns 401 or 403 | Authorizer or WAF blocks OPTIONS | Exempt OPTIONS, or use HTTP API CORS |
| Preflight returns 404 | No OPTIONS route or wrong stage path | Add the OPTIONS method or CORS config |
| "Request header field X is not allowed" | Header not in Access-Control-Allow-Headers | Add it (lower-case) |
| "must not be the wildcard ... credentials mode is include" | Wildcard origin with cookies | Use an exact origin, or remove credentials |
| "multiple values" for Allow-Origin | Two layers add the header | Disable one |
| Works in Chrome after a hard refresh only | Cached preflight (Max-Age) or CDN | Wait for max age, purge cache, include Origin in the cache key |
| 500 appears as a CORS error | Error response generated outside CORS handling | Fix the 500, and ensure error paths carry CORS headers |
| Works locally, fails in the environment | Origin list missing the environment's origin | Add the exact origin in that environment's configuration |
Cost and cleanup
Cost label: free. The probe and the local ASP.NET Core app need no AWS resources. If you test against a sandbox HTTP API, API Gateway cost at this volume is negligible (⚠ VERIFY current request pricing), but delete the API afterwards.
# Only if you created a sandbox HTTP API
aws apigatewayv2 delete-api --api-id <api-id> --profile learn-sandbox
# Confirm nothing tagged for this lesson remains
aws resourcegroupstaggingapi get-resources --tag-filters Key=Lab,Values=m17-playbook-cors --profile learn-sandboxExercises
- 🟢 Guided: Run the ASP.NET Core sample locally with
http://localhost:5173in the allowed list. Use the probe with that origin and then withhttps://evil.example. Compare the verdicts. - 🟡 Challenge: Write three xUnit tests for
CorsRules.Evaluate: duplicate allow-origin values, wildcard with credentials, and a missingauthorizationinAccess-Control-Allow-Headers. - 🔴 Live problem: "The new web front end works for GET but every POST to
/v1/paymentsfails with a CORS error. Mobile works. The API is a REST API with a Lambda authorizer and the team says CORS is enabled." You have the console and CloudWatch Logs. List your checks in order and the narrowest fix.
Assignment
Add a CORS section to your capstone API's README: which layer owns CORS, the exact origins per environment, the headers and methods allowed, and the pipeline test that replays a preflight and a hostile-origin check. Commit with fictional domains.
Solutions
With http://localhost:5173 the app echoes that exact origin in Access-Control-Allow-Origin, includes the allowed methods and headers, and the probe prints "a browser would accept this preflight". With https://evil.example the app sends no allow-origin header, so the probe reports "No Access-Control-Allow-Origin header" and exits with code 2. Why: ASP.NET Core only echoes origins from the explicit list, which is exactly the behaviour you want to test automatically.
Build a header dictionary with new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase). Test 1: ["Access-Control-Allow-Origin"] = new[] { "https://a.example", "https://b.example" } should yield a problem containing "more than once". Test 2: allow-origin * and withCredentials: true should yield the wildcard-with-credentials problem. Test 3: Access-Control-Allow-Headers of content-type with request headers authorization,content-type yields one problem naming authorization. Assert with Assert.Contains(problems, p => p.Contains("authorization")). Why: because the rules are a pure function, they run in milliseconds with no network and guard against regressions.
GET works because it is a simple request with no preflight, while POST with application/json and Authorization triggers a preflight. Checks: (1) in the Network tab, find the OPTIONS request and its status; (2) in API Gateway, does the resource have an OPTIONS method, and does the method have authorization set to None (a Lambda authorizer on OPTIONS would deny a tokenless preflight)? (3) does the OPTIONS integration response list Access-Control-Allow-Headers with authorization and content-type, and Access-Control-Allow-Methods with POST? (4) does the real POST response from the Lambda include Access-Control-Allow-Origin? Narrowest fix: add or repair the OPTIONS method without the authorizer, list exactly the needed headers and methods and the single origin, and add the allow-origin header in the Lambda response, then add gateway-response headers for 4XX and 5XX. Why: the two places a REST API most often fails are the OPTIONS route and the real response, and both are separate from "CORS is enabled" in the console.
Knowledge check
Answer: CORS is enforced by browsers only. curl never checks the response headers against an origin, so it succeeds even when the server sends no CORS headers.
Answer: The browser does not send credentials such as the Authorization header on the preflight, so the authorizer denies it and the response has no CORS headers.
Answer: No. With credentials, the origin must be an exact value and Access-Control-Allow-Credentials must be true.
Answer: The browser sees two values and rejects the response. Let one layer own CORS.
Answer: After UseRouting and before UseAuthentication and UseAuthorization, so preflights and responses carry CORS headers before auth can reject them.
Interview questions
- Explain CORS in two sentences. A browser blocks scripts from reading cross-origin responses unless the server's headers allow that origin. It protects users' browsers, not the server.
- A front-end developer says "the API has a CORS bug". What do you do? Check the Network tab for the preflight and real response statuses, replay the preflight, and find which layer answered.
- How do you configure CORS on API Gateway? HTTP APIs have a built-in setting. REST APIs need an OPTIONS method plus headers on real and gateway error responses.
- Is CORS a security control for your API? Only for browsers. Authentication and authorisation remain mandatory.
- How could you avoid CORS entirely? Serve the front end and API from one origin, for example paths behind one CloudFront distribution.
Certification practice
A single-page application calls an API Gateway REST API with a Lambda proxy integration. Preflight OPTIONS requests succeed, but actual POST responses are blocked by the browser with a CORS error. What is the most likely cause?
A. The Lambda function does not return Access-Control-Allow-Origin in its proxy response.
B. The API stage needs a larger throttle limit.
C. The OPTIONS method must be removed.
D. The Lambda memory is too low.
Answer: A. With proxy integration the function must add the CORS headers itself to the real response. Throttling, removing OPTIONS and memory do not cause this symptom.
A bank's web app on https://app.example must call an authenticated API on another domain from the browser. Which CORS configuration is most secure and works?
A. Allow * origins and credentials.
B. Allow the specific origin https://app.example, only the required methods and headers.
C. Reflect any Origin header back in Access-Control-Allow-Origin.
D. Disable CORS in API Gateway and rely on the firewall.
Answer: B. Exact origin and least privilege. A is rejected by browsers, C lets any site read responses, and D does not make cross-origin browser calls work.
A security review finds an API returning Access-Control-Allow-Origin equal to whatever origin the request sends, with Access-Control-Allow-Credentials: true. What is the risk?
A. Higher latency. B. Any malicious website can make authenticated requests from a user's browser and read the responses. C. TLS certificate expiry. D. DNS cache poisoning.
Answer: B. Reflection with credentials removes the same-origin protection. The other options are unrelated to the configuration.
Completion checklist
- I can explain preflight requests and why
Authorizationtriggers one - I can find out which layer answered a preflight
- I ran the probe against a good and a hostile origin
- I can state the wildcard-with-credentials rule
- I know the ASP.NET Core middleware order for CORS
- I ran the cleanup steps and confirmed nothing tagged
m17-playbook-corsremains
Key takeaways
- CORS is a browser rule: replay the preflight and read the real response status.
- One layer owns CORS per path. Duplicated headers break it.
- The preflight carries no credentials, so authorizers must not guard OPTIONS.
- Error responses need CORS headers too, or a 401 looks like a CORS error.
- The fix is an exact origin list, never a wildcard with credentials or a reflected origin.
Further reading
- Configuring CORS for an HTTP API
- Enable CORS in ASP.NET Core
- Previous playbook: 502, 503 and 504 from an ALB or API Gateway
- Next playbook: S3 bucket accidentally public
- Related: Module 17 overview
Independent learning resource — not affiliated with, endorsed or sponsored by Amazon Web Services. AWS and related marks are trademarks of Amazon.com, Inc. or its affiliates. All banking data in examples is fictional. Sample architectures are for learning and are not automatically compliant with GDPR, PCI DSS or any banking regulation.
Playbook: 502, 503 and 504 from an ALB or API Gateway
Work out which hop returned a gateway error, read the load balancer and API Gateway evidence, and fix target health, keep-alive, idle-timeout and integration-timeout mismatches without guessing.
Playbook: S3 bucket accidentally public
Contain an exposed S3 bucket in minutes with Block Public Access, work out who changed it and who read from it using CloudTrail and access logs, preserve evidence, and hand a factual timeline to the incident and data protection teams.