Skip to content

CORS Configuration

FastAPI Guard provides comprehensive CORS (Cross-Origin Resource Sharing) configuration options. Set enable_cors=True on SecurityConfig and the middleware activates CORS automatically — no separate setup call is required.


Basic CORS Setup

Enable CORS with default settings:

config = SecurityConfig(enable_cors=True, cors_allow_origins=["*"])
app.add_middleware(SecurityMiddleware, config=config)

Advanced Configuration

Configure specific CORS settings:

config = SecurityConfig(
    enable_cors=True,
    cors_allow_origins=["https://example.com", "https://api.example.com"],
    cors_allow_methods=["GET", "POST", "PUT", "DELETE"],
    cors_allow_headers=["*"],
    cors_allow_credentials=True,
    cors_expose_headers=["X-Custom-Header"],
    cors_max_age=600,
)
app.add_middleware(SecurityMiddleware, config=config)

Origin Patterns

Use patterns to match multiple origins:

config = SecurityConfig(
    enable_cors=True,
    cors_allow_origins=["https://*.example.com", "https://*.api.example.com"],
)
app.add_middleware(SecurityMiddleware, config=config)

Credentials Support

Enable credentials support for authenticated requests:

config = SecurityConfig(
    enable_cors=True,
    cors_allow_credentials=True,
    cors_allow_origins=[
        "https://app.example.com"  # Must be specific origin when using credentials
    ],
)
app.add_middleware(SecurityMiddleware, config=config)

Custom Headers

Configure custom headers for CORS:

config = SecurityConfig(
    enable_cors=True,
    cors_allow_headers=["Authorization", "Content-Type", "X-Custom-Header"],
    cors_expose_headers=["X-Custom-Response-Header"],
)
app.add_middleware(SecurityMiddleware, config=config)