skip to content

In FastAPI, what does the scopes dict passed to OAuth2PasswordBearer do in the /docs page and when a request arrives?

level: juniorimportance: should knowfreq 30%

answer

  1. what the schema says vs what runs
  2. scope name mapped to a description
  3. the Authorize dialog's checkboxes
  4. flows.password.scopes in the security scheme
  5. form_data.scopes on the token route

basics

~20 s

The scopes dict on OAuth2PasswordBearer only documents scopes: FastAPI writes it into the OpenAPI security scheme, and the /docs Authorize dialog offers each as a checkbox. At request time the class extracts the bearer token and checks no scope.

solid answer

~40 s

`OAuth2PasswordBearer(tokenUrl="token", scopes={"items:read": "Read items.", ...})` maps each scope name to a human-readable description. FastAPI copies that dict into `flows.password.scopes` of the generated OpenAPI security scheme, so the **Authorize** dialog in `/docs` lists the scopes as checkboxes, and the ticked ones reach the token route through the space-separated `scope` form field, which `OAuth2PasswordRequestForm` exposes as the list `form_data.scopes`. At request time the instance does one job: read the `Authorization` header, return the text after `Bearer`, or reject a missing or non-bearer header. It never decodes the token and never compares scopes. Enforcement needs your own dependency, declared with `Security(..., scopes=[...])`, that reads `SecurityScopes` and compares it with the scopes inside the token.

code

python · 30 lines
python
import json
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
from fastapi.testclient import TestClient

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={
        "items:read": "Read inventory items.",
        "items:write": "Create and change inventory items.",
        "me": "Read your own profile.",
    },
)

app = FastAPI()


@app.get("/items")
def list_items(token: Annotated[str, Depends(oauth2_scheme)]):
    # The scheme hands over the raw token string; no scope was checked.
    return {"token_seen": token}


client = TestClient(app)
print(client.get("/items", headers={"Authorization": "Bearer read-only-token"}).json())
# {'token_seen': 'read-only-token'}
print(json.dumps(app.openapi()["components"]["securitySchemes"], indent=1))
# "flows": {"password": {"scopes": {...the dict...}, "tokenUrl": "token"}}

go deeper

for a junior

Recall that the dict is a name-to-description map that feeds the docs and the schema, and that the class only hands your code the bearer token string.

for a middle

Explain the path from the dict to flows.password.scopes, the Authorize checkboxes, the scope form field and form_data.scopes, and name where a scope is actually required.

for a senior

Point out that nothing ties the dict to enforcement, so a review must confirm that a checking dependency exists and that the dict matches the scopes routes declare.

for a principal

Treat the scope list as part of the API contract clients see in the schema, and make keeping it aligned with enforced scopes a team convention backed by a test.

## What the dict is `OAuth2PasswordBearer` is FastAPI's class for the OAuth2 **password flow** with a bearer token. Its constructor takes a required `tokenUrl` (the path of the route that issues tokens) and an optional `scopes` argument typed `dict[str, str] | None`. Each **key** is a scope name, the string a token carries to say what it may do; each **value** is the description a person reads when choosing scopes. For an inventory API the declaration might be: ```python oauth2_scheme = OAuth2PasswordBearer( tokenUrl="token", scopes={ "items:read": "Read inventory items.", "items:write": "Create and change inventory items.", "me": "Read your own profile.", }, ) ``` If `scopes` is left out, FastAPI stores an empty dict. ## Where it shows up: the schema and the docs UI FastAPI turns every security class used by a route into an entry under `components.securitySchemes` in the OpenAPI document it generates. For `OAuth2PasswordBearer` that entry has `type: oauth2` and a `flows.password` object holding the `tokenUrl` and the **whole scopes dict**. A scheme no route depends on is not written at all. Swagger UI at `/docs` reads that entry and draws the **Authorize** dialog: - a username and password form for the password flow; - one checkbox per scope, labelled with your description; - a request to `tokenUrl` carrying the ticked scopes in the single `scope` form field, separated by spaces. On the token route, `OAuth2PasswordRequestForm` splits that field, so `form_data.scopes` is a list such as `["items:read", "me"]`. What goes into the issued token is decided by your token route, not by the dict. ## What happens when a request arrives When a route depends on `oauth2_scheme`, FastAPI calls the instance with the request. The call: 1. reads the `Authorization` header; 2. if it is missing or its scheme is not `Bearer`, raises the class's not-authenticated error (or returns `None` when `auto_error=False`); 3. otherwise returns the text after `Bearer` as a plain string. That is all. The dict is **not consulted**: the class does not decode a JWT, does not read a scope claim and does not compare anything with the declared scopes. A token that holds only `items:read` passes the scheme exactly as an admin token does. | Concern | Handled by the scopes dict? | Where it is handled | |---|---|---| | Listing scopes in OpenAPI | Yes | `flows.password.scopes` | | Offering scopes in `/docs` | Yes | the Authorize dialog | | Choosing which scopes a token gets | No | your token route | | Requiring a scope on a route | No | `Security(dep, scopes=[...])` | | Rejecting a token that lacks it | No | your dependency reading `SecurityScopes` | ## Where enforcement actually lives Requiring a scope takes two pieces you write: a route or dependency declares `Security(get_current_principal, scopes=["items:write"])`, and `get_current_principal` declares a `SecurityScopes` parameter, decodes the token and raises `HTTPException` when a required scope is missing. The dict and the route declarations are independent: a route can require a scope the dict never lists and FastAPI raises no error; the scope then simply cannot be ticked in `/docs`. Keeping the two in step is a review habit, not something the framework checks. ## Reading the docs page Two different scope lists show up in `/docs`, and they come from different places: - the **Authorize dialog** lists every scope in the dict, whether or not any route requires it; - each **operation** shows a lock, and its security requirement lists only the scopes that route declares through `Security(..., scopes=[...])`, for example `items:write` on `POST /items`. A route that depends on the scheme without `Security` scopes shows the lock with an empty list. Comparing the two lists is a quick sanity check: a scope offered in the dialog that no operation requires is dead weight, and a scope an operation requires that the dialog does not offer cannot be obtained from the docs page. ## Common misreadings - Treating the dict as an allow-list that filters tokens: it filters nothing. - Assuming the scheme validates a JWT because the tutorial pairs it with one: decoding happens in your dependency. - Expecting the ticked checkboxes to end up in the token automatically: the token route decides. - Reading the descriptions as security policy: they are labels for people choosing scopes, and changing one changes only the docs.

  • What happens if a route requires a scope that the scopes dict does not list?
    The route still works: FastAPI does not cross-check `Security(..., scopes=[...])` against the dict, and the scope appears in that operation's OpenAPI security requirement. The only effect is in `/docs`, whose Authorize dialog cannot offer the unlisted scope, so nobody can request it there. Keep the dict and the routes' declared scopes in step.
  • What does the token route receive when a user ticks items:read and me in the Authorize dialog?
    A form post with `username`, `password` and one `scope` field holding `items:read me`. `OAuth2PasswordRequestForm` splits that string on whitespace, so `form_data.scopes` is `["items:read", "me"]`. The route then decides which of those the user may actually hold before writing them into the token.

  • The scopes dict makes OAuth2PasswordBearer reject tokens lacking those scopes.
  • OAuth2PasswordBearer decodes the JWT and reads its scope claim for you.
  • A scope missing from the dict makes FastAPI fail at startup.
  • Scopes ticked in the docs UI land in the token without the token route deciding.