skip to content

OAuth2 Password Bearer

OAuth2PasswordBearer reads a bearer token and OAuth2PasswordRequestForm takes the login form. Interviewers ask how get_current_user checks a JWT and why unknown users still hash a password.

on this pageshow

explore

questions

5

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

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

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