skip to content

Security Dependencies

FastAPI's security classes are dependencies that read credentials, raise 401 with a WWW-Authenticate header and document the scheme in OpenAPI. Interviewers probe get_current_user and its scopes.

on this pageshow

explore

questions

16

In FastAPI, what does an OAuth2PasswordBearer(tokenUrl="token") dependency check on each request, and what does it leave to your code?

level: middleimportance: must knowfreq 72%

answer

  1. one request header
  2. scheme compared case-insensitively
  3. hands back a plain string
  4. 401 with a Bearer challenge
  5. tokenUrl only feeds the docs

basics

~20 s

OAuth2PasswordBearer reads the Authorization header, checks that the scheme is Bearer and returns the rest as a string, answering 401 with WWW-Authenticate: Bearer otherwise. It never validates the token; decoding it and loading the user are your code's job.

solid answer

~40 s

An `OAuth2PasswordBearer` instance is a callable dependency. On each request it reads `Authorization`, splits it at the first space, compares the scheme to `bearer` case-insensitively and returns the remainder, stripped, as a `str`. If the header is missing or uses another scheme, it raises `HTTPException` 401 with `detail` "Not authenticated" and `WWW-Authenticate: Bearer`; with `auto_error=False` it returns `None` instead. It does not decode, verify or look anything up: `Bearer not-a-jwt` reaches your code as `"not-a-jwt"`, and a bare `Bearer` arrives as an empty string. `tokenUrl` creates no route; it is written into the OpenAPI password flow so the docs' Authorize dialog knows where to post credentials.

code

python · 31 lines
python
from typing import Annotated

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

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()


@app.get("/users/me")
async def read_me(token: Annotated[str, Depends(oauth2_scheme)]):
    return {"token_seen": token}  # nothing has validated this string yet


client = TestClient(app)

r = client.get("/users/me")
assert r.status_code == 401
assert r.json() == {"detail": "Not authenticated"}
assert r.headers["www-authenticate"] == "Bearer"

r = client.get("/users/me", headers={"Authorization": "Basic YWxpY2U6eA=="})
assert r.status_code == 401

r = client.get("/users/me", headers={"Authorization": "bearer not-a-jwt"})
assert r.json() == {"token_seen": "not-a-jwt"}

r = client.get("/users/me", headers={"Authorization": "Bearer"})
assert r.json() == {"token_seen": ""}
print("all assertions passed")

go deeper

for a junior

Recall that the scheme reads the Authorization: Bearer header, hands back the token string and answers 401 when the header is missing.

for a middle

Walk through the header parsing, the 401 body and challenge header, what auto_error changes, and why tokenUrl is documentation rather than a route.

for a senior

Spot endpoints that use the raw token without a validating dependency, and explain the empty-string and wrong-scheme cases a review should cover.

for a principal

Make one validating current-user dependency the team's only sanctioned way to read identity, so no endpoint depends on the bare scheme by accident.

## What the class is for FastAPI's security utilities are dependencies that also describe themselves in the OpenAPI schema. **`OAuth2PasswordBearer`** is the one for APIs whose clients obtain a token by posting a username and password and then send it as `Authorization: Bearer <token>`. You create one instance at module level and depend on it: ```python oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def read_me(token: Annotated[str, Depends(oauth2_scheme)]): ... ``` Because the class inherits from FastAPI's security base class, FastAPI adds an `oauth2` security scheme with a `password` flow to the schema and attaches it to every operation that depends on the instance, directly or through sub-dependencies. That is where the **Authorize** button and the lock icons in Swagger UI come from. ## What happens on each request The instance's `__call__` is short, and knowing it line by line answers most interview follow-ups: 1. It reads `request.headers.get("Authorization")`. 2. It splits the value at the first space into a scheme and a parameter, and strips the parameter. 3. If the header is missing, or the scheme lowercased is not `"bearer"`, it either raises the error from `make_not_authenticated_error()` (when `auto_error=True`, the default) or returns `None` (when `auto_error=False`). 4. Otherwise it returns the parameter as a `str`. The error is an `HTTPException` with **status 401**, `detail` **"Not authenticated"** and the header **`WWW-Authenticate: Bearer`**. Because a dependency raises it, the path operation never runs. | `Authorization` header | Result | |---|---| | absent | 401, "Not authenticated", `WWW-Authenticate: Bearer` | | `Basic YWxpY2U6eA==` | the same 401: any other scheme is treated as missing | | `bearer abc` | `"abc"`: the scheme match ignores case | | `Bearer abc ` | `"abc"`: surrounding spaces are stripped | | `Bearer not-a-jwt` | `"not-a-jwt"`: nothing checks its content | | `Bearer` | `""`: an empty string, and the endpoint still runs | ## What it leaves to you The class only **extracts** the token. Everything that makes it trustworthy is your code, normally a `get_current_user` dependency that depends on the scheme: - verifying the signature and expiry, typically with PyJWT's `jwt.decode`; - reading the subject claim and loading that user; - turning every failure, including an empty string, into a 401 of your own; - any permission decision about what the user may do. An endpoint that takes `token: Annotated[str, Depends(oauth2_scheme)]` and uses the value without such a step is authenticated in appearance only: any string after `Bearer`, even an empty one, gets in. ## `tokenUrl` and the docs `tokenUrl` is **metadata**. It goes into the schema's password flow (`{"tokenUrl": "token", "scopes": {}}`) so that the docs' Authorize dialog knows where to post `username` and `password`. It does not create that path operation; you write `POST /token` yourself with `OAuth2PasswordRequestForm`. The docs use the relative form `"token"` on purpose: it resolves against the page's URL, so the dialog keeps working when the API is served under a prefix such as `/api/v1`. An absolute `"/token"` would point the dialog at the host's root instead. The parameter is camel-case because it mirrors the OpenAPI field name. `refreshUrl` is documented the same way and is also only metadata. ## Details worth knowing - **One extraction per request.** If several dependencies in one request depend on the same `oauth2_scheme` instance, FastAPI's per-request dependency cache calls it once and shares the string. - **`auto_error=False`** makes the token optional: the dependency yields `None` for a missing or non-Bearer header, and your code decides what anonymous callers get. - **401 is not 403.** The class answers a missing credential with 401 and a Bearer challenge; 403 is for a known caller who lacks permission, which this class never decides. - **`scheme_name`** defaults to the class name and is what the schema calls the scheme. ## Reading it in a code review When a pull request touches a route protected by this class, a reviewer can check four things quickly: 1. Does the endpoint depend on a validating dependency such as `get_current_user`, or on the bare scheme? Only the first proves anything about the caller. 2. Does that dependency reject every failure, the empty string included, with its own 401 and a `WWW-Authenticate: Bearer` header? 3. Is `tokenUrl` relative and does it match the real login route, so the docs' Authorize dialog works wherever the app is mounted? 4. If `auto_error=False` is set, does the code handle `None` deliberately rather than passing it on as if it were a token?

  • Three dependencies in one FastAPI request all depend on the same oauth2_scheme instance; how often does it read the header?
    Once. FastAPI caches each dependency's result for the duration of a request, so the scheme's `__call__` runs once and every dependent receives the same string. Only a declaration with `use_cache=False` would call it again.
  • Why do FastAPI's docs write tokenUrl="token" rather than "/token"?
    A relative URL resolves against where the docs page is served. Behind a proxy that mounts the API at `/api/v1`, `"token"` becomes `/api/v1/token` and the Authorize dialog still reaches the login route, while `"/token"` would post to the host's root and fail.
  • What should get_current_user do with the empty string a bare Authorization: Bearer header produces?
    Treat it like any other invalid token. `jwt.decode` raises a PyJWT `InvalidTokenError` subclass for an empty string, so a dependency that catches that base class and raises its 401 handles the case without a special branch.

  • OAuth2PasswordBearer verifies the JWT signature and expiry for you
  • tokenUrl creates the /token login route automatically
  • A missing token makes OAuth2PasswordBearer answer 403 Forbidden
  • The header must spell Bearer with a capital B
  • An absolute tokenUrl keeps the docs working under a path prefix
open as a page

In a FastAPI app, how does a get_current_user dependency turn a bearer JWT into a user, and where does get_current_active_user fit?

level: middleimportance: must knowfreq 70%

basics

~20 s

get_current_user depends on the OAuth2PasswordBearer scheme, decodes the token with PyJWT's jwt.decode and a fixed algorithms list, reads sub, loads that user and raises 401 on any failure. get_current_active_user depends on it and rejects disabled accounts.

open as a page

In FastAPI, what does Security() add over Depends(), and what does it leave for your own code to do?

level: middleimportance: must knowfreq 40%

basics

~20 s

fastapi.Security declares a dependency exactly as Depends does, plus a scopes list that FastAPI passes down to SecurityScopes and writes into the operation's OpenAPI security. It checks nothing; your dependency must compare those scopes with the token.

open as a page

In FastAPI, how do APIKeyHeader, APIKeyQuery and APIKeyCookie differ, and what does each one hand your endpoint?

level: juniorimportance: should knowfreq 40%

basics

~20 s

All three read one named value from the request (a header, a query parameter or a cookie) and return it as a string. A missing or empty value gets 401, but none of them checks that the key is valid.

open as a page

In FastAPI, what does a token endpoint built on OAuth2PasswordRequestForm accept, and what must it send back?

level: juniorimportance: should knowfreq 55%

basics

~10 s

OAuth2PasswordRequestForm reads form-encoded username and password fields, plus optional scope, grant_type, client_id and client_secret. The endpoint itself must return JSON with access_token and token_type set to bearer.

open as a page

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%

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.

open as a page

In FastAPI, how do you protect an internal metrics endpoint with HTTPBasic, and what must your own dependency check?

level: middleimportance: should knowfreq 35%

basics

~10 s

HTTPBasic decodes the Authorization header into HTTPBasicCredentials or answers 401 with WWW-Authenticate: Basic. Your dependency compares username and password with secrets.compare_digest on bytes and raises 401 with the same header on a mismatch.

open as a page

In FastAPI, how does auto_error=False on HTTPBearer let a product page personalise only when a token is present, and what can go wrong?

level: middleimportance: should knowfreq 35%

basics

~20 s

With auto_error=False, HTTPBearer returns None instead of raising 401 when no Bearer credential is sent, so the page can serve anonymous callers. A token that is present still has to be verified by your dependency, which should reject a bad one.

open as a page

A FastAPI route guarded only by Depends(APIKeyHeader(name="X-API-Key")) accepts any non-empty key: why, and how should the check be built?

level: middleimportance: should knowfreq 40%

basics

~20 s

APIKeyHeader only extracts the header and rejects a missing one; it never compares the value. Wrap it in your own dependency that verifies the key, raises 401 with WWW-Authenticate on a mismatch, and attach that dependency to the router.

open as a page

In FastAPI, what do OAuth2AuthorizationCodeBearer and OpenIdConnect do with a request, and what must your own dependency still verify?

level: middleimportance: should knowfreq 25%

basics

~20 s

Both only read the Authorization header and describe a scheme in OpenAPI. OAuth2AuthorizationCodeBearer returns the text after Bearer; OpenIdConnect returns the whole header and never fetches its discovery URL. Token validation and scope checks are your dependency's job.

open as a page

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%

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.

open as a page

After upgrading FastAPI past 0.122, partner clients that expected 403 from APIKeyHeader for a missing key now get 401: what changed, and how do you respond?

level: seniorimportance: should knowfreq 25%

basics

~20 s

FastAPI 0.122 made its security classes answer a missing credential with 401 and a WWW-Authenticate challenge instead of 403. Update clients and tests; if one cannot change yet, subclass and override make_not_authenticated_error to return a 403.

open as a page

A FastAPI login endpoint built on OAuth2PasswordRequestForm sends the same 401 for unknown users and wrong passwords, yet response times reveal which usernames exist; why, and what fixes it?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The unknown-user branch returns before the slow Argon2 verify, so it answers far faster than a real account. Verify the submitted password against a DUMMY_HASH on that branch, and keep the 401 detail and headers identical.

open as a page

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?

level: seniorimportance: should knowfreq 35%

basics

~10 s

FastAPI 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.

open as a page

Reviewing a FastAPI API whose routes declare Security() scopes, what could let a read-only reporting token still reach the write endpoints?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Declared scopes enforce nothing alone. Look for write routes on Depends or on Security over the scheme, a checker ignoring SecurityScopes, an any() or substring comparison, and a token route granting whatever scopes the client requests.

open as a page

Your FastAPI service issues its own JWTs from an OAuth2PasswordRequestForm login endpoint; when should a lead keep that design, and when hand sign-in to an identity provider?

level: principalimportance: nice to knowfreq 25%

basics

~20 s

Keep in-app login while one first-party client needs plain username and password and the team can own hashing, signing keys, revocation and abuse controls. Delegate once several apps, single sign-on, MFA or audit duties arrive; the FastAPI app then only verifies tokens.

open as a page