CORS

Cross-Origin Resource Sharing (CORS) is a security mechanism implemented in web browsers to protect against unauthorized access to resources on different domains. It allows a server to specify which domains can access its resources and which HTTP methods are permitted for those resources. CORS works by adding an extra HTTP header to a server’s responses, indicating whether a browser should be allowed to access the requested resource. This mechanism enables web applications hosted on different domains to share resources, such as images, scripts, or fonts while maintaining security and preventing malicious attacks. By controlling access to resources, CORS ensures that web applications can only interact with the resources they are authorized to access, thus preventing cross-site scripting (XSS) attacks and other security vulnerabilities.

Read more about this on the official documentation https://fastapi.tiangolo.com/tutorial/cors/.

Working in main.py, include the following import (FastAPI re-exports Starlette’s middleware, so starlette.middleware.cors works too):

main.pypython
from fastapi.middleware.cors import CORSMiddleware

Add the following code, where origins will include any domain authorised to access your application, for example:

main.pypython
origins = [
    "http://localhost:8000",
    "https://localhost:8000",
    "https://www.exampleforyou.net:8000",
    "https://www.exampleforyou.net",
]

main_app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["X-Process-Time", "X-Health-Check"],
)

A few points worth knowing:

  • Origins are listed explicitly. With allow_credentials=True (needed later for cookie-based login), never use allow_origins=["*"]. Browsers refuse credentialed requests to a wildcard origin.
  • Browsers only let JavaScript read custom response headers that are listed in expose_headers, so the X-Process-Time header from the previous section and X-Health-Check are exposed here.
  • CORS is enforced by the browser. Tools like curl ignore it, so it doesn’t replace authentication.

The complete main.py now looks like this:

main.pypython
import time

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware  # NEW

from api import health_api
from config.settings import settings

main_app = FastAPI()

# CORS
origins = [                               # NEW
    "http://localhost:8000",              # NEW
    "https://localhost:8000",             # NEW
    "https://www.exampleforyou.net:8000", # NEW
    "https://www.exampleforyou.net",      # NEW
]                                         # NEW

main_app.add_middleware(                  # NEW
    CORSMiddleware,                       # NEW
    allow_origins=origins,                # NEW
    allow_credentials=True,               # NEW
    allow_methods=["*"],                  # NEW
    allow_headers=["*"],                  # NEW
    expose_headers=["X-Process-Time", "X-Health-Check"],  # NEW
)                                         # NEW

# Middleware
@main_app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.perf_counter()
    response = await call_next(request)
    process_time = time.perf_counter() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response

def configure():
    configure_routing()

def configure_routing():
    main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])

if __name__ == '__main__':
    configure()
    uvicorn.run(main_app,
                host=settings.CONF_MAIN_APP_HOST,
                port=settings.CONF_MAIN_APP_PORT)
else:
    configure()

You can check a browser-style preflight request with curl. An allowed origin is echoed back in access-control-allow-origin, and any other origin gets no such header:

curl -si -X OPTIONS http://localhost:8000/api/v1/health \
  -H 'Origin: https://www.exampleforyou.net' \
  -H 'Access-Control-Request-Method: GET'
HTTP/1.1 200 OK
access-control-allow-methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, QUERY
access-control-max-age: 600
access-control-allow-credentials: true
access-control-allow-origin: https://www.exampleforyou.net