Home / OCI

OCITroubleshootingIntermediate

OCI API Gateway CORS errors: failing preflight, missing Access-Control-Allow-Origin and credentialed requests

The browser blocks calls to an OCI API Gateway deployment with a CORS error while curl works. Reproduce the preflight with curl, then fix the deployment's CORS policy for origins, methods, headers and credentials.

Deepak Bhardwaj7 min read

Applies toOCI API Gateway deployments (global and route-level CORS request policies); OCI CLI; any browser front end calling the gateway

Symptom

A single-page app calling an API Gateway deployment fails in the browser, while the same request from curl or Postman works. The browser console shows one of these:

  • No 'Access-Control-Allow-Origin' header is present on the requested resource
  • Response to preflight request doesn't pass access control check
  • Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response
  • The value of the 'Access-Control-Allow-Origin' header ... must not be the wildcard '*' when the request's credentials mode is 'include'
  • The 'Access-Control-Allow-Origin' header contains multiple values

CORS is enforced by the browser. The gateway and backend are usually working. What's wrong is the set of CORS headers the gateway returns. In OCI API Gateway those headers come from a CORS request policy in the deployment specification. You can set it globally for the deployment, on individual routes, or both.

1. Reproduce the preflight with curl

Browsers send an OPTIONS preflight before any "non-simple" request, such as one with Authorization, a JSON Content-Type, or a PUT/DELETE. Send the same preflight yourself and read the headers that come back:

GW=https://<gateway-hostname>/<deployment-path-prefix>/orders

curl -si -X OPTIONS "$GW" \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type,authorization"

A working preflight returns a 2xx status with headers like these:

access-control-allow-origin: https://app.example.com
access-control-allow-methods: GET,POST
access-control-allow-headers: content-type,authorization
access-control-max-age: 600

Then check the actual request. The browser also needs Access-Control-Allow-Origin on that response:

curl -si -X POST "$GW" \
  -H "Origin: https://app.example.com" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{}' | grep -i "^access-control"

Use the browser's exact origin string, including scheme and port. https://app.example.com and https://app.example.com:8443 are different origins.

2. Map the error to the cause

Browser error / curl result Likely cause Fix
No Access-Control-Allow-Origin on either response No CORS policy on the deployment or on this route Add a CORS request policy (section 4)
Header missing only for some origins The origin isn't in allowedOrigins (scheme or port differs, or there's a trailing slash) Add the exact origin string
Preflight fails for PUT/DELETE/PATCH Method not in allowedMethods Add the method, or use ["*"]
"Request header field X is not allowed" Header not in allowedHeaders Add authorization, content-type and any custom headers
App can't read a response header (e.g. x-request-id) Header not in exposedHeaders Add it to exposedHeaders
"must not be the wildcard '*' when credentials mode is 'include'" allowedOrigins: ["*"] with cookies or withCredentials List explicit origins and set isAllowCredentialsEnabled: true
"contains multiple values" Backend also sets CORS headers Remove CORS handling from the backend, or stop it duplicating
Works on one route, fails on another A route-level CORS policy differs from the global one Check the route's requestPolicies.cors
Preflight returns 401/404 The OPTIONS request isn't matched by a CORS policy, so it falls through to auth or routing Confirm the policy covers this route and origin, then check execution logs

3. Read the current CORS configuration

Find the deployment and dump its specification:

oci api-gateway deployment list --compartment-id $C --all \
  --query 'data.items[].{name:"display-name",id:id,prefix:"path-prefix",state:"lifecycle-state"}' \
  --output table

D=ocid1.apideployment.oc1..xxxx
oci api-gateway deployment get --deployment-id $D \
  --query 'data.specification' > spec.json

Look at the global and per-route CORS blocks:

jq '.["request-policies"].cors' spec.json
jq '.routes[] | {path, methods, cors: .["request-policies"].cors}' spec.json

The CLI prints keys in kebab-case (request-policies, allowed-origins). Deployment specification files you write and pass back with --specification use camelCase (requestPolicies, allowedOrigins). Keep a clean camelCase copy of the specification in source control instead of round-tripping the CLI output. If you can't, convert the keys before you update.

Tip

When a route has its own CORS policy, that route's settings apply instead of the global ones. A route that "ignores" a change you made globally usually has its own cors block.

4. Fix the CORS policy

A deployment-wide policy for a browser app that sends a bearer token:

{
  "requestPolicies": {
    "cors": {
      "allowedOrigins": ["https://app.example.com", "https://staging.app.example.com"],
      "allowedMethods": ["GET", "POST", "PUT", "DELETE"],
      "allowedHeaders": ["authorization", "content-type", "x-correlation-id"],
      "exposedHeaders": ["x-request-id"],
      "isAllowCredentialsEnabled": false,
      "maxAgeInSeconds": 600
    }
  },
  "routes": [
    {
      "path": "/orders",
      "methods": ["GET", "POST"],
      "backend": { "type": "HTTP_BACKEND", "url": "https://orders.internal.example.com/orders" }
    }
  ]
}

What the fields do:

  • allowedOrigins is required. Use exact origins. * matches any origin, and null matches requests from file: origins. Avoid both in production.
  • allowedMethods lists the methods allowed on the actual request.
  • allowedHeaders lists the request headers the browser may send. Missing authorization is the most common cause of a failing preflight.
  • exposedHeaders lists the response headers JavaScript may read.
  • isAllowCredentialsEnabled must be true if the app sends cookies or uses credentials: 'include'. The browser then rejects a wildcard origin, so list the origins explicitly.
  • maxAgeInSeconds sets how long the browser caches the preflight result. Keep it short while you troubleshoot.

Apply the change:

oci api-gateway deployment update --deployment-id $D \
  --specification file://spec.json --force \
  --wait-for-state SUCCEEDED --wait-for-state FAILED

Warning

--specification replaces the whole specification: every route, auth policy and rate limit. Start from the full current specification, change only the cors block, and diff before applying. Leaving out a route or the authentication policy takes that route down or exposes it unauthenticated.

If the work request fails, read the reason:

oci api-gateway work-request list --compartment-id $C \
  --query 'data.items[0].{id:id,status:status,op:"operation-type"}'
oci api-gateway work-request-error list --work-request-id <wr-ocid>

Repeat the curl preflight from section 1. Then hard-refresh the browser, or open a private window, so a cached preflight from the old policy isn't reused.

5. Duplicate headers from the backend

If the backend framework (Express cors(), Spring @CrossOrigin, Flask-CORS) also adds CORS headers, the browser can see two Access-Control-Allow-Origin values and reject the response. Choose one owner. With API Gateway in front, the simplest option is to let the gateway own CORS and turn it off in the application:

# Compare what the backend returns directly (from inside the VCN) with what the gateway returns
curl -si https://orders.internal.example.com/orders -H "Origin: https://app.example.com" | grep -i "^access-control"
curl -si "$GW" -H "Origin: https://app.example.com" | grep -i "^access-control"

6. Check execution logs

If curl still doesn't return the headers you expect, enable execution logs on the deployment (Logging, service API Gateway, category execution, log level Information) and search them while you reproduce:

oci logging-search search-logs \
  --search-query "search \"$C/<log-group-ocid>/<log-ocid>\" | where data.requestMethod = 'OPTIONS' | sort by datetime desc" \
  --time-start $(date -u -d '-15 min' +%Y-%m-%dT%H:%M:%SZ) \
  --time-end $(date -u +%Y-%m-%dT%H:%M:%SZ)

Field names in API Gateway log records vary between log types and versions. Run an unfiltered search first, check which fields your records contain, then add the where clause.

Prevent it next time

  • Keep the deployment specification in Git, as JSON or Terraform (oci_apigateway_deployment), and review CORS changes like code.
  • Define CORS once at deployment level, and use route-level policies only when a route really needs different settings.
  • Add the curl preflight from section 1 to the deployment pipeline for every allowed origin. Fail the release if access-control-allow-origin is missing.
  • Never ship allowedOrigins: ["*"] for APIs that use cookies or carry user data.
  • When the front end adds a custom request header, add it to allowedHeaders in the same change.