CORS & HTTPS Redirects
Relevant source files
The following files were used as context for generating this wiki page:
Starlette provides dedicated middleware components to handle Cross-Origin Resource Sharing (CORS) and mandatory HTTPS redirection. These components are implemented as ASGI middleware, allowing them to intercept incoming requests and outgoing responses to enforce security policies and web standards.
The CORSMiddleware manages complex browser-based security handshakes, while HTTPSRedirectMiddleware ensures all traffic is securely encrypted by redirecting non-secure HTTP requests to their HTTPS counterparts.
CORSMiddleware
The CORSMiddleware handles both "simple" requests and "preflight" requests from browsers. It validates the Origin header of incoming requests against a whitelist of allowed origins and injects the necessary Access-Control-* headers into the response.
Logic and Data Flow
When a request arrives, the middleware checks for an Origin header. If absent, the request passes through to the application normally. If present, the middleware determines if the request is a preflight (an OPTIONS request containing the Access-Control-Request-Method header) or a simple request.
Sources: starlette/middleware/cors.py:74-91
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
allow_origins | Sequence[str] | () | List of origins allowed to make cross-site requests. Use ['*'] for all. |
allow_methods | Sequence[str] | ('GET',) | List of allowed HTTP methods. ['*'] allows all standard methods. |
allow_headers | Sequence[str] | () | List of allowed HTTP request headers. ['*'] allows all. |
allow_credentials | bool | False | Indicates if cookies/authentication are supported for cross-site requests. |
allow_origin_regex | str | None | A regex string to match allowed origins. |
expose_headers | Sequence[str] | () | Headers that the browser is allowed to access. |
max_age | int | 600 | Maximum time (seconds) to cache preflight responses. |
allow_private_network | bool | False | Whether to allow Access-Control-Request-Private-Network. |
Sources: starlette/middleware/cors.py:18-31
Preflight Handling
Preflight requests are responded to directly by the middleware without calling the underlying application. The middleware validates the requested method and headers. If any validation fails, it returns a 400 Bad Request with a descriptive body; otherwise, it returns a 200 OK.
Sources: starlette/middleware/cors.py:102-143
HTTPSRedirectMiddleware
HTTPSRedirectMiddleware enforces that all incoming requests use the https or wss schemes. If a request is received over plain http or ws, the middleware intercepts it and returns a redirect response to the secure equivalent.
Redirect Logic
The middleware inspects the scope["scheme"]. If the scheme is http or ws, it generates a new URL using the https or wss protocol and returns a RedirectResponse with a 307 Temporary Redirect status code. This preserves the original request method during the redirect.
Sources: starlette/middleware/httpsredirect.py:14-25 (implied structure), tests/middleware/test_https_redirect.py:15-30
Implementation Details
The middleware uses Starlette's URL datastructure to manipulate the connection details. It specifically handles port mapping:
- If the original request is
httpon port80, it redirects tohttps(default port). - If the original request is on a non-standard port (e.g.,
123), it preserves that port in thehttpsredirect.
Sources: tests/middleware/test_https_redirect.py:31-45, starlette/responses.py:175-184
Security Interactions
Vary Header Management
To prevent caching issues where a cached response for one origin is served to another, CORSMiddleware automatically manages the Vary header.
- If
allow_credentialsisTrueor specific origins are defined (not*), the middleware addsVary: Originto the response. - This ensures that the cache key includes the request's origin.
Sources: starlette/middleware/cors.py:166-170, tests/middleware/test_cors.py:315-345
Credential Handling
When allow_credentials is set to True, the Access-Control-Allow-Origin header cannot be set to the wildcard *. In this scenario, the middleware must reflect the specific origin provided in the request back to the browser.
# starlette/middleware/cors.py:156-160
# If credentials are allowed, then we must respond with the specific origin instead of '*'.
if self.allow_all_origins and self.allow_credentials:
self.allow_explicit_origin(headers, origin)
Sources: starlette/middleware/cors.py:156-160, tests/middleware/test_cors.py:40-55
Summary
Starlette's CORS and HTTPS redirect systems provide essential security layers for modern web applications. CORSMiddleware offers granular control over cross-origin interactions, supporting regex matching, credentialed requests, and private network access. Complementing this, HTTPSRedirectMiddleware ensures transport security by strictly enforcing encrypted communication through 307 redirects. Together, these modules facilitate compliance with browser security models and best practices for secure web services.