Overly permissive FastAPI CORS settings

Overly permissive FastAPI CORS settings

Description

For a request made with credentials mode include, the browser blocks access to a response with Access-Control-Allow-Origin: *. If the response instead names an untrusted request origin and sets Access-Control-Allow-Credentials: true, that site may read it.

Potential impact

If the request carries a session cookie, the exposed API response may contain the user’s account data.

Remediation

  • With allow_credentials=True, set explicit allow_origins, allow_methods and allow_headers in CORSMiddleware, as FastAPI and Starlette specify. Avoid ["*"] and catch-all allow_origin_regex patterns such as .* or .+, including their anchored forms.
  • Keep separate allow-lists for each environment and allow only the production frontends that need access. Enforce authentication, authorization and any required CSRF checks on the server.

Examples

Before

python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

After

python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type"],
)

The revised configuration names https://app.example.com as its credentialed origin and explicitly lists GET, POST, Authorization and Content-Type.

References