skip to content

In FastAPI, how does a SecurityScopes parameter collect required scopes along a dependency chain, and what is scope_str for?

level: middleimportance: should knowfreq 35%

answer

  1. injected like Request, not from the client
  2. parents first, then the dependency's own
  3. per path operation, per branch
  4. plain Depends passes them through
  5. space-joined for a header

basics

~20 s

A SecurityScopes parameter receives every scope that Security() declarations add on the path from the route down to that dependency, deduplicated and per route. scope_str is the same list joined with spaces, ready for a WWW-Authenticate scope attribute.

solid answer

~40 s

`SecurityScopes` is a special parameter type, like `Request`: FastAPI fills it, the client never sends it. Its `scopes` list holds the scopes declared with `Security(..., scopes=[...])` on every step from the path operation down to the dependency that declares it, parents first and duplicates removed. A plain `Depends` in the middle passes the list through unchanged; sibling branches do not see each other's scopes. So one central `get_current_principal` gets `["items:read", "me"]` for one route and `[]` for another, and can check whatever that route needs. `scope_str` is `" ".join(scopes)`, the space-separated form OAuth2 uses on the wire; the FastAPI docs put it in the `WWW-Authenticate` header as `Bearer scope="..."` so a client learns which scopes the route requires.

code

python · 46 lines
python
from typing import Annotated

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

oauth2_scheme = OAuth2PasswordBearer(
    tokenUrl="token",
    scopes={"items:read": "Read items.", "items:write": "Change items.", "me": "Own profile."},
)


def get_current_principal(
    security_scopes: SecurityScopes,
    token: Annotated[str, Depends(oauth2_scheme)],
):
    return {"scopes": security_scopes.scopes, "scope_str": security_scopes.scope_str}


def get_active_principal(
    principal: Annotated[dict, Security(get_current_principal, scopes=["me"])],
):
    return principal


app = FastAPI()


@app.get("/me/items")
def my_items(
    principal: Annotated[dict, Security(get_active_principal, scopes=["items:read"])],
):
    return principal


@app.get("/me")
def me(principal: Annotated[dict, Depends(get_active_principal)]):
    return principal


client = TestClient(app)
headers = {"Authorization": "Bearer any-token"}
print(client.get("/me/items", headers=headers).json())
# {'scopes': ['items:read', 'me'], 'scope_str': 'items:read me'}
print(client.get("/me", headers=headers).json())
# {'scopes': ['me'], 'scope_str': 'me'}

go deeper

for a junior

Remember that SecurityScopes is filled by FastAPI with the scopes the route requires, and that scope_str is the same list as one space-separated string.

for a middle

Walk a chain of Security and Depends declarations and state the exact list a checker sees for each route, including that Depends passes scopes through.

for a senior

Use the per-route list to keep one central checker for the whole API, and explain the double call and the merged OpenAPI requirement when branches differ.

for a principal

Settle whether scopes are declared at the route, the router or a shared dependency, so the scope list each checker sees stays predictable as the API grows.

## What `SecurityScopes` is `fastapi.security.SecurityScopes` is a small class with two attributes: - `scopes`, a `list[str]` of required OAuth2 scope names; - `scope_str`, the same names joined with single spaces, computed as `" ".join(self.scopes)`. You never construct it. When a dependency declares a parameter annotated `SecurityScopes`, FastAPI recognises the type (as it does `Request` or `BackgroundTasks`) and injects an instance built for **that route and that position in the dependency graph**. Nothing in it comes from the request; it describes what the code requires, not what the token holds. ## How the list is built FastAPI analyses each path operation's dependencies once, when the route is registered, and records for every node two lists: the scopes it declares itself (from `Security(..., scopes=[...])`) and the scopes its parents passed down. The list a `SecurityScopes` parameter receives is the parents' list followed by the node's own scopes, with duplicates dropped. Take an inventory API: ```python def get_current_principal(security_scopes: SecurityScopes, token: Annotated[str, Depends(oauth2_scheme)]): ... def get_active_principal( p: Annotated[dict, Security(get_current_principal, scopes=["me"])]): ... @app.get("/me/items") def my_items(p: Annotated[dict, Security(get_active_principal, scopes=["items:read"])]): ... ``` For `/me/items` the route adds `items:read`, then `get_active_principal` adds `me`, so `get_current_principal` sees `["items:read", "me"]` and `scope_str` is `"items:read me"`. | Route declares | Middle step | `security_scopes.scopes` in the checker | |---|---|---| | `Security(get_active_principal, scopes=["items:read"])` | `Security(..., scopes=["me"])` | `["items:read", "me"]` | | `Depends(get_active_principal)` | `Security(..., scopes=["me"])` | `["me"]` | | `Depends(get_current_principal)` | none | `[]` | Three rules follow from the mechanism: 1. **Per route.** The same checker gets a different list for each path operation, which is what lets one central dependency enforce every route's needs. 2. **`Depends` passes scopes through.** A plain `Depends` step adds nothing but does not drop what came from above; a route's `Security(..., scopes=["items:write"])` still reaches a checker two `Depends` levels down. 3. **Branches stay separate.** If a route has two dependencies, each declaring different scopes over the same checker, each branch's checker sees only its own branch's list. ## What `scope_str` is for OAuth2 writes a set of scopes on the wire as one string, names separated by spaces. `scope_str` gives you that form without joining by hand. The FastAPI documentation uses it to build the challenge header of the error it raises: - with required scopes, `WWW-Authenticate: Bearer scope="items:read me"`; - with none, plain `Bearer`. A client that receives the error can read which scopes the route asked for and request a token that carries them. ## Interactions worth knowing - **Caching.** A dependency that uses scopes is cached per request under its callable plus the sorted set of scopes it sees, so a checker reached through two branches with different lists runs twice. Dependencies that use no scopes are still shared. - **OpenAPI.** The schema merges scopes per security scheme for the whole operation. A route with two branches requiring `me` and `items:write` documents both together, even though each checker run tests only its own branch's list. - **Decorator and router lists.** `Security` inside `dependencies=[...]` on a decorator or an `APIRouter` contributes its scopes to that branch just as a parameter does. ## What it does not do `SecurityScopes` holds requirements only. Comparing them with the token, deciding the status code and building the response are the job of the dependency that declares it. ## Common mistakes - **Reading it as the token's scopes.** The list says what the code needs; what the token was granted comes from decoding the token. - **Declaring it on the path operation function.** Scopes declared through the route's own `Security(...)` parameters flow down into those dependencies, not up; a `SecurityScopes` parameter on the route function itself receives `[]`. Declare it in the checker. - **Hard-coding the required scope in the checker.** A checker that tests `"items:write" in granted` regardless of `security_scopes` enforces one rule everywhere and ignores what each route declared. - **Building the header by hand.** Joining with commas or another separator produces a challenge clients cannot parse; `scope_str` already uses the space-separated OAuth2 form. - **Expecting the docs order.** The FastAPI documentation lists the tutorial's chain as `["me", "items"]`; the code builds parents first, so the route's own scope comes first. Compare as a set and the order never matters.

  • Does a plain Depends() in the middle of the chain drop the scopes declared above it?
    No. Each node receives its parent's accumulated list whether it was declared with `Depends` or `Security`; `Depends` simply adds nothing of its own. A route declaring `Security(plain_step, scopes=["items:write"])`, where `plain_step` uses `Depends(get_current_principal)`, still delivers `["items:write"]` to the checker.
  • Why can a route's OpenAPI security list more scopes than any single checker run requires?
    The schema generator merges, per security scheme, the scopes of every branch of the operation into one requirement. If one dependency branch needs `me` and another `items:write`, the operation documents both together, while at runtime each branch's checker sees and tests only its own list. Both still have to pass, so the documented union is what a client needs.

  • SecurityScopes holds the scopes granted inside the client's token.
  • SecurityScopes sees only the scopes declared directly on its own dependency.
  • A plain Depends() step resets the required scope list to empty.
  • scope_str is a ready WWW-Authenticate header value including Bearer.
  • Every route that shares a checker gets the same SecurityScopes list.

Assumes FastAPI 0.143; scope propagation was fixed in 0.122.1 and per-scope caching narrowed in 0.123.0.