In a FastAPI inventory API, a valid token lacking items:write calls a write endpoint; how should the scope check fail, and with which status?
answer
- who raises: framework or your code
- authenticated is not authorized
- insufficient_scope in the challenge
- scope_str names what was required
- the docs example uses 401
basics
~10 sFastAPI sends nothing for a missing scope; your checking dependency must raise. Use 403 with WWW-Authenticate: Bearer error="insufficient_scope", scope="..." built from SecurityScopes.scope_str, and keep 401 for missing, invalid or expired credentials.
solid answer
~40 sIn FastAPI 0.143 the security classes answer only a missing or non-bearer header (401, `WWW-Authenticate: Bearer`). A token that is valid but lacks `items:write` passes them; the only thing that can refuse it is the dependency declared with `Security(..., scopes=["items:write"])` that compares `security_scopes.scopes` with the token's scopes. The FastAPI tutorial raises 401 `Not enough permissions` there, but the bearer-token specification describes this case as `insufficient_scope` with 403: the credentials worked, the permission did not, and a 401 invites clients to re-authenticate in a loop. So raise `HTTPException(403, headers={"WWW-Authenticate": f'Bearer error="insufficient_scope", scope="{security_scopes.scope_str}"'})`, require every scope rather than any, and keep 401 for unknown, expired or forged tokens.
code
python · 61 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Security, status
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."},
)
# Stand-in for decoding a real token: token -> granted scopes.
GRANTED = {"reporting-token": {"items:read"}, "admin-token": {"items:read", "items:write"}}
def get_current_principal(
security_scopes: SecurityScopes,
token: Annotated[str, Depends(oauth2_scheme)],
):
challenge = "Bearer"
if security_scopes.scopes:
challenge = f'Bearer scope="{security_scopes.scope_str}"'
granted = GRANTED.get(token)
if granted is None: # unknown, expired or forged token: authentication failed
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": challenge},
)
missing = [s for s in security_scopes.scopes if s not in granted]
if missing: # valid token, not enough permission: authorization failed
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={
"WWW-Authenticate": f'Bearer error="insufficient_scope", '
f'scope="{security_scopes.scope_str}"'
},
)
return {"token": token}
app = FastAPI()
@app.post("/items")
def create_item(
principal: Annotated[dict, Security(get_current_principal, scopes=["items:write"])],
):
return {"created": True}
client = TestClient(app)
for token in (None, "forged", "reporting-token", "admin-token"):
headers = {"Authorization": f"Bearer {token}"} if token else {}
r = client.post("/items", headers=headers)
print(token, r.status_code, r.headers.get("www-authenticate"))
# None 401 Bearer
# forged 401 Bearer scope="items:write"
# reporting-token 403 Bearer error="insufficient_scope", scope="items:write"
# admin-token 200 Nonego deeper
Remember that FastAPI itself never rejects a missing scope; your dependency raises HTTPException, and the status code you pick is part of the API.
Explain the split between the scheme's 401 for missing credentials and your own check, and show how scope_str goes into the WWW-Authenticate header.
Argue for 403 with insufficient_scope, require every scope, keep error bodies free of granted claims, and pin the four outcomes with tests.
Set one failure contract for authentication and permission errors across the team's services, so clients and dashboards can tell bad tokens from missing grants.
## Who answers which failure A request to `POST /items` in an inventory API can fail at three different points, and FastAPI owns only the first. | Situation | Who raises | Status and header | |---|---|---| | No `Authorization` header, or not `Bearer` | `OAuth2PasswordBearer` with `auto_error=True` | 401, `WWW-Authenticate: Bearer` | | Token present but unknown, expired or forged | your checking dependency | 401, `WWW-Authenticate: Bearer ...` | | Token valid, `items:write` not granted | your checking dependency | 403 recommended, `error="insufficient_scope"` | The first row is framework behaviour: since 0.122 the security classes return 401 with a `WWW-Authenticate` header for missing credentials. The other two exist only if you write them. A route declared with `Security(get_current_principal, scopes=["items:write"])` is refused only when `get_current_principal` reads its `SecurityScopes` and raises. ## Why 403 for a missing scope **401 Unauthorized** means the request lacks valid authentication; a client that gets it should obtain fresh credentials and retry. **403 Forbidden** means the server understood who is calling and refuses anyway. A reporting client holding a valid read-only token is in the second case. Answering 401: - tells a well-behaved client its token is bad, so it may refresh or log in again and receive another read-only token, then retry in a loop; - blurs the line in monitoring between broken credentials and permission gaps, which need different fixes. The OAuth 2.0 bearer-token specification (RFC 6750) names this case `insufficient_scope` and says the resource server SHOULD answer 403 and MAY add a `scope` attribute naming what is needed. The FastAPI tutorial on scopes raises 401 with `detail="Not enough permissions"` for the same check; that keeps the example short, but it is the example's choice, not a framework rule, and FastAPI enforces neither code. ## Building the response Inside the checker, with `security_scopes: SecurityScopes` declared: 1. Decode and validate the token; on any failure raise 401 with `WWW-Authenticate: Bearer` (plus `scope="..."` if you like). 2. Turn the token's scope claim into a **set of whole names**. 3. Collect every entry of `security_scopes.scopes` that is not in that set; **all** must be present, not any. 4. If some are missing, raise: ```python raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions", headers={"WWW-Authenticate": f'Bearer error="insufficient_scope", scope="{security_scopes.scope_str}"'}, ) ``` `scope_str` is the required list joined with spaces, so the header tells the client exactly which scopes the route needed. `HTTPException`'s `headers` argument carries the header into FastAPI's default exception handler, which writes it on the response. ## What not to put in the response From the defender's side, the error says what was **required**, never what the token **holds** or why the user lacks it: - no echo of the token or its decoded claims; - no list of the user's roles; - the same message for every missing scope, so probing reveals nothing beyond the route's documented requirement, which OpenAPI already publishes. ## Testing the contract The status codes are an API contract clients code against, so pin them: - no header returns 401; - a forged token returns 401; - a read-only token on a write route returns 403 with `insufficient_scope`; - a token with every scope returns 200. Running these with an in-process test client takes milliseconds and catches the day someone swaps `Security` for `Depends` on a write route. ## Common mistakes - **One exception for everything.** Reusing the 401 credentials exception for the scope branch, as the tutorial does, merges two failures clients must handle differently. - **Forgetting the challenge header.** A 401 or 403 without `WWW-Authenticate` leaves the client to guess what went wrong; the header is where the required scope is announced. - **Checking scopes after side effects.** The comparison belongs in the dependency, which runs before the route body; a check written inside the route after a database write is too late.
- The FastAPI tutorial raises 401 "Not enough permissions" for a missing scope. Why not copy it?The tutorial keeps one exception for every failure to stay short. In production a 401 tells clients their credentials failed, so token-refreshing clients retry pointlessly and monitoring merges bad tokens with permission gaps. The bearer-token specification recommends 403 with `insufficient_scope` for this case; FastAPI enforces neither, so pick 403 and document it.
- Should the check pass when the token holds any one of the required scopes?No. `security_scopes.scopes` is the union of everything the route and its dependencies declared, and each entry is a requirement. Test that every entry is in the token's scope set; an `any()` check lets a token with `me` reach a route that also needs `items:write`.
- Where does FastAPI 0.122's change from 403 to 401 fit into this?It concerns the security classes themselves when credentials are missing: since 0.122 they send 401 with `WWW-Authenticate`. A scope failure is raised by your own dependency with whatever status you choose, so that change neither causes nor fixes the 401-versus-403 question for scopes.
- FastAPI returns 403 by itself when a token lacks a declared scope.
- A valid token missing a scope should get 401 so the client logs in again.
- Passing when the token holds any one of the required scopes is enough.
- The error body should list the scopes the token actually holds.
- The 0.122 change to 401 also changed how scope failures are reported.
Assumes FastAPI 0.143; since 0.122 the security classes return 401 with WWW-Authenticate for missing credentials, while scope failures remain your code's choice.