CORS: Which Web Pages May Call Your API

A browser lets a web page read answers only from its own origin unless the API allows it, and FastAPI's CORSMiddleware with an allow-list of origins lets the club's own pages in, which protects people's browsers but never stops a script or a tool.

Journeyman · FastAPI · Web Development · Updated

By

After this lesson you can

  • Explain the same-origin rule, CORS and preflight requests, and why CORS never stops a script or a tool from calling an API
  • Allow only an API's own web pages to call it from a browser with CORSMiddleware and an allow-list of origins

Key takeaways

  • An origin is an address's scheme, host and port together, such as http://localhost:5500. A browser lets a page read answers only from its own origin, unless the other server allows it.
  • CORS is how an API allows other origins. Its answer carries an Access-Control-Allow-Origin header that names the origin it allows.
  • Before a request that could change data, such as a PATCH with a token, the browser asks first with an OPTIONS request, called a preflight.
  • CORSMiddleware with a list of origins names the pages on the list in its answers, and leaves the header out for every other page.
  • CORS is a rule browsers follow. Scripts, tools and other servers ignore it, so it never replaces signing in.

The first time a web page calls an API you built, there's a good chance it fails with a red message about CORS in the browser's console. Nearly every front end meets it, usually on the afternoon it first talks to its own API. This lesson shows what the browser is protecting, and how your API tells it which pages are welcome.

This chapter's example is Bean There Coffee Club, a coffee subscription club whose API (members, orders, each member's favorite roast) is about to go online. A volunteer's web page for the club runs, while it's being built, at http://localhost:5500, and asks the API for the roasts with fetch("http://127.0.0.1:8000/roasts"). The docs page gets the roasts with no trouble. The web page gets nothing, and the browser's console (F12) says the request was blocked by CORS policy.

The browser's console with a red error: the page at http://localhost:5500 was blocked by CORS policy from reading http://127.0.0.1:8000/roasts, because the answer has no Access-Control-Allow-Origin header

The browser's guest list

Think of an office building with a front desk. People who work there walk straight in. A visitor gets in only if the company they're visiting has put their name on its guest list; the front desk only reads the list. The browser is the front desk, your API is the company, and the visitor is a web page. Where a page comes from is its origin: its scheme (http or https), its host and its port, together. Python's urllib.parse splits an address into those parts:

from urllib.parse import urlsplit


def origin(address):
    parts = urlsplit(address)
    return f"{parts.scheme}://{parts.netloc}"


print(origin("http://localhost:5500/order.html"))
print(origin("http://127.0.0.1:8000/roasts"))
print(origin("https://www.beanthere.example/menu"))
print(origin("https://beanthere.example/menu"))
http://localhost:5500
http://127.0.0.1:8000
https://www.beanthere.example
https://beanthere.example

A different port is a different origin, and so is a different host: localhost and 127.0.0.1 are two origins even on one computer, and so are www.beanthere.example and beanthere.example. The browser's rule, called the same-origin policy, is that a page may read answers only from its own origin. CORS (said "kors", short for Cross-Origin Resource Sharing) is how a server puts other origins on its guest list: its answer carries an Access-Control-Allow-Origin header that names the origin it allows. The docs page never had this problem, because FastAPI serves it from the API's own origin.

The browser as a building's front desk with a guest list: the club's page is on the list and its request walks in to the API; a page from another site isn't on the list and is stopped; a script walks past the desk through a side door, because only browsers check the list

Putting the club's pages on the list

FastAPI comes with CORSMiddleware. A middleware is code that every request passes through on its way to your routes, and every answer passes through on its way back, like a checkpoint at the building's door. Add it to the app with app.add_middleware, and give it the list of origins that may call the API, an allow-list:

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

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://www.beanthere.example", "http://localhost:5500"],
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)

The first origin is the club's real site, and the second is the page while it's being built. allow_methods and allow_headers say what those pages may send. A browser puts an Origin header on every request a page makes to another origin, so you can play the browser in a test, the way Testing an API with TestClient sends requests:

from fastapi.testclient import TestClient

from main import app

client = TestClient(app)

for origin in ["http://localhost:5500", "https://coffee-deals.example"]:
    response = client.get("/roasts", headers={"Origin": origin})
    print(response.status_code, response.headers.get("access-control-allow-origin"))
200 http://localhost:5500
200 None

Both answer 200 OK with the roasts: the list doesn't stop the API from answering. For the page on the list, the answer names its origin, so the browser hands the roasts to the page. For https://coffee-deals.example, a site that isn't on the list, the header isn't there (None), so the browser keeps the roasts from that page.

allow_origins=["*"] (read "star", meaning every origin) fits a public API anyone may read, such as a bus timetable. For an API with members' data, name the origins. (A page that signs in with cookies also needs allow_credentials=True, which browsers accept only with named origins. The club's page sends a token instead.)

Preflight: asking before sending

Changing a favorite roast is a PATCH to /members/me, with a JSON body and a token in the Authorization header. A request like that could change data, so the browser phones ahead first. It sends an OPTIONS request, called a preflight, asking whether that method and those headers are allowed from this origin, and CORSMiddleware answers it:

response = client.options(
    "/members/me",
    headers={
        "Origin": "http://localhost:5500",
        "Access-Control-Request-Method": "PATCH",
        "Access-Control-Request-Headers": "authorization,content-type",
    },
)
print(response.status_code, response.text)
print(response.headers["access-control-allow-origin"])
print(response.headers["access-control-allow-methods"])
200 OK
http://localhost:5500
GET, POST, PATCH, DELETE

Only after a yes like this does the browser send the real PATCH. Ask from https://coffee-deals.example instead, and the middleware answers 400 Bad Request with the text Disallowed CORS origin. Ask for a method that isn't in allow_methods, such as PUT, and it's 400 with Disallowed CORS method. Either way, the browser never sends the real request.

What CORS doesn't protect

CORS is a rule browsers follow, and only browsers:

  • Scripts, tools and other servers ignore it. TestClient got the roasts while pretending to be https://coffee-deals.example, and a Python script or curl would too.
  • Even in a browser, a plain GET reaches your API. When the volunteer's page was blocked, the API's terminal showed GET /roasts arrive and answer 200. The browser received the roasts and kept them from the page.

So CORS protects the people who use your API through a browser: a page on another site can't use a member's browser to read the club's data. It doesn't protect the API from anyone who sends requests some other way. That job belongs to signing in, as Requiring a Signed-In User builds it, to the rate limits in Rate Limits and Security Headers, and to checking every request, as The Attacks to Expect: Injection and Mass Assignment shows.

Sources

Check yourself

2 questions to try on the lesson page.

So what

When your front end and your API live at different origins, CORS is how they're introduced, and knowing it's the browser's rule tells you both how to fix the red console message and why it never replaces a real check on the server.

Key terms

Related