A FastAPI API called with cookies from a browser app on another origin fails once credentials are sent; how should CORSMiddleware be configured, and why not allow_origins=["*"]?
answer
- restrictive defaults on every argument
- credentials flag defaults to off
- exact origins, not a wildcard
- wildcard plus credentials echoes origin
- preflight answered without routing
basics
~20 sList the frontend's exact origins in allow_origins, set allow_credentials=True, and name the methods and headers it uses. With credentials on, allow_origins=["*"] makes Starlette echo any Origin back with credentials allowed, so any website could read responses sent with users' cookies.
solid answer
~30 s`CORSMiddleware` defaults are restrictive: no origins, `allow_methods=("GET",)`, no extra `allow_headers`, `allow_credentials=False`, `max_age=600`. With `allow_credentials` left off, responses carry no `Access-Control-Allow-Credentials: true`, and a wildcard origin is sent as a literal `*`, so the browser discards credentialed responses. The fix is `allow_origins=["https://app.example.com"]`, `allow_credentials=True`, and the real methods and request headers. Do not combine `["*"]` with credentials: the docs forbid it, but Starlette 1.7 accepts it and reflects whatever `Origin` arrives together with `Access-Control-Allow-Credentials: true`. Preflights are answered by the middleware itself, 200 or 400 `Disallowed CORS ...`, and a disallowed simple request still reaches the endpoint; only the headers are missing.
code
python · 19 linesfrom fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"], # exact origins, never "*" here
allow_credentials=True, # send Access-Control-Allow-Credentials: true
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Content-Type", "X-CSRF-Token"],
expose_headers=["X-Process-Time"], # let browser code read it
max_age=600,
)
@app.get("/me")
async def me() -> dict[str, str]:
return {"user": "alice"}go deeper
Know the arguments: allow_origins, allow_methods, allow_headers, allow_credentials, expose_headers, and that their defaults allow almost nothing.
Explain why credentials need an exact origin plus Access-Control-Allow-Credentials, and why a GET-only default fails a PATCH preflight with 400.
Review configs from the defender's side: a wildcard with credentials reflects any origin, a loose regex admits crafted origins, and CORS never blocks the server-side call.
Decide whether the frontend talks to the API cross-origin at all, and own the allow-list as configuration reviewed like any other access rule.
## What CORSMiddleware does in a FastAPI app **CORS** (cross-origin resource sharing) is how a server tells a browser which other **origins**, meaning scheme plus host plus port, may read its responses. FastAPI uses Starlette's `CORSMiddleware`, re-exported as `fastapi.middleware.cors.CORSMiddleware`, and you add it with `app.add_middleware(...)`. It handles two kinds of request: - **Preflight requests**: an `OPTIONS` request carrying `Origin` and `Access-Control-Request-Method`. The middleware answers these **itself**, with `200 OK` or `400` and a body such as `Disallowed CORS origin` or `Disallowed CORS method`. No route, dependency or other inner middleware runs, and you do not need an `OPTIONS` path operation. - **Simple and actual requests**: any request with an `Origin` header. The request passes through to your app as normal, and the middleware adds CORS headers to the response. ## The defaults are restrictive | Argument | Default | Meaning | |---|---|---| | `allow_origins` | empty | no cross-origin reads allowed | | `allow_methods` | `("GET",)` | a `POST` or `PATCH` preflight is refused | | `allow_headers` | empty, plus `Accept`, `Accept-Language`, `Content-Language`, `Content-Type` | a custom header such as `X-CSRF-Token` is refused | | `allow_credentials` | `False` | no `Access-Control-Allow-Credentials` header | | `expose_headers` | empty | browser code reads only the basic response headers | | `max_age` | `600` | seconds a browser may cache a preflight answer | ## Why it fails only with credentials When the frontend sends cookies (for example a fetch with credentials included), the browser accepts the response only if it names the exact origin in `Access-Control-Allow-Origin` and carries `Access-Control-Allow-Credentials: true`. With `allow_credentials=False` the second header never appears. With `allow_origins=["*"]` and no credentials, the middleware sends a literal `*`, which a browser will not accept for a credentialed call. Both configurations work for anonymous calls and break as soon as cookies are involved, which is exactly the symptom. ## The safe configuration 1. List each frontend origin exactly: `allow_origins=["https://app.example.com"]`. The middleware then mirrors the matching origin and adds `Vary: Origin`, so caches keep per-origin answers apart. 2. Set `allow_credentials=True`. 3. Name the methods the frontend uses (`allow_methods=["GET", "POST", "PATCH", "DELETE"]`) and the request headers it sends (`allow_headers=["Content-Type", "X-CSRF-Token"]`). 4. Add any custom response header the frontend must read to `expose_headers`. 5. Add `CORSMiddleware` last, so it is the outermost user middleware and answers preflights first. ## Why the wildcard is dangerous with credentials The FastAPI and Starlette docs say none of `allow_origins`, `allow_methods` or `allow_headers` may be `["*"]` when `allow_credentials=True`. Nothing enforces it. In Starlette 1.7, `allow_origins=["*"]` plus `allow_credentials=True` makes the middleware copy **whatever `Origin` the request carried** into `Access-Control-Allow-Origin` and add `Access-Control-Allow-Credentials: true`, on both preflight and normal responses. Any website a logged-in user visits can then call your API with that user's cookies and read the answers. `allow_headers=["*"]` likewise mirrors whatever headers a preflight asks for. A quick review of an existing app therefore checks: 1. Does any `CORSMiddleware` call combine `allow_credentials=True` with a `"*"` in `allow_origins`? 2. Are the allowed origins loaded from configuration per environment, so a development origin such as a local port does not reach production? 3. Does a request from an unlisted origin come back without `Access-Control-Allow-Origin`? 4. Does a preflight for an unlisted method or header get `400`? `allow_origin_regex` has the same trap in a subtler form. The pattern must match the whole origin, but `.*` also matches `/`, `#` and `@`: `https://.*\.example\.com` accepts `https://evil.com/.example.com`. Starlette's docs recommend a character class such as `[a-zA-Z0-9-]+` instead. ## Preflight caching Every successful preflight carries `Access-Control-Max-Age`, `600` seconds unless you set `max_age`. The browser may reuse that answer for later calls with the same method and headers instead of sending a new `OPTIONS` request. Two practical effects follow: a higher value saves a round trip per call, and after you tighten the allow-list, browsers that cached a permissive answer can keep using it until it expires. ## What CORS does not do CORS controls whether the **browser lets a page read** a response. A simple request from a disallowed origin still reaches your endpoint, runs, and gets a 200; the middleware only leaves the CORS headers out. Endpoints that change state under cookie authentication still need their own protection against cross-site requests; the browser side of CORS is covered in the frontend material on CORS.
- How do you support several preview frontends on subdomains with credentials in FastAPI's CORSMiddleware?Use `allow_origin_regex` with a tight pattern such as `r"https://[a-z0-9-]+\.preview\.example\.com"` alongside `allow_credentials=True`. The pattern is matched against the whole origin, but avoid `.*` or `.+`, which also match `/`, `#` and `@` and let crafted origins pass. Matching origins are mirrored back individually, never as `*`.
- Why does a FastAPI preflight for PATCH return 400 even though the PATCH route exists?`CORSMiddleware` answers preflights itself and checks `Access-Control-Request-Method` against `allow_methods`, which defaults to `("GET",)`. A PATCH preflight therefore gets `400 Disallowed CORS method` without reaching the router. Add the method to `allow_methods`; the route's existence is irrelevant to the preflight.
- Does CORSMiddleware in FastAPI stop a request from a disallowed origin from running the endpoint?No. For a request that needs no preflight, the middleware passes it to the app, the endpoint runs and returns its normal status, and only the CORS headers are left out, so the browser hides the response from the page. Treat CORS as read permission for browsers, not as access control on the server.
Allowing every origin with credentials is like a doorman who, asked whether a name is on the guest list, simply repeats the name back: every visitor walks in, which defeats keeping a list.
- Sets allow_origins=["*"] with allow_credentials=True and calls it safe.
- Believes CORSMiddleware rejects requests from disallowed origins with a 403.
- Adds an OPTIONS path operation to make preflights succeed.
- Thinks allow_methods allows every method by default.
- Assumes the constructor raises an error for wildcard plus credentials.
Assumes FastAPI 0.143 on Starlette 1.7; FastAPI accepts Starlette from 0.46 and CORSMiddleware is Starlette's, so the installed Starlette release decides its exact headers.