python config_error ai_generated true

RuntimeError: CORS: Cannot use allow_credentials with allow_origins='*'

ID: python/fastapi-cors-credentials-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

FastAPI CORS configuration uses allow_credentials=True with allow_origins=['*'], which is not allowed by the CORS specification.

generic

中文

FastAPI CORS配置使用了allow_credentials=True和allow_origins=['*'],CORS规范不允许这样做。

Workarounds

  1. 95% success Specify explicit origins instead of wildcard
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["https://example.com"],
        allow_credentials=True,
    )
  2. 85% success Remove allow_credentials if wildcard is needed
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=False,
    )

Dead Ends

Common approaches that don't work:

  1. Setting allow_credentials to False without changing origins 60% fail

    May break functionality that requires credentials.

  2. Ignoring the error and deploying anyway 95% fail

    CORS errors will occur in the browser.