How does OAuth2PasswordBearer work in FastAPI?
OAuth2PasswordBearer is a FastAPI security scheme class that declares a dependency expecting a Bearer token in the Authorization header.
How it works:
- You create an instance with
tokenUrlpointing to your login endpoint - It tells FastAPI's auto-docs (Swagger UI) where to send username/password to get a token
- When used as a dependency, it extracts the token from the
Authorization: Bearer <token>header - If no token is present, it returns a
401 Unauthorizedautomatically - It does not validate the token itself -- that is your responsibility
What tokenUrl does:
- It is only used by the Swagger UI "Authorize" button to know which endpoint to POST credentials to
- It does not create the endpoint -- you must define it yourself
- It should be a relative URL path (e.g.,
"token"or"/auth/token")
Integration with OpenAPI:
FastAPI uses this to generate the correct OpenAPI security scheme, enabling the lock icon and "Authorize" dialog in Swagger UI.
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
# When used as dependency:
# 1. Reads Authorization header
# 2. Strips "Bearer " prefix
# 3. Returns raw token string
# 4. Raises 401 if missing
@app.get("/protected")
def protected(token: str = Depends(oauth2_scheme)):
user = validate_and_decode(token)
return user
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer
from fastapi.testclient import TestClient
app = FastAPI()
# Declare the OAuth2 scheme -- tokenUrl is for Swagger UI
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/items")
def read_items(token: str = Depends(oauth2_scheme)):
"""Token is the raw Bearer token string."""
return {"token": token}
# --- Test it ---
client = TestClient(app)
# Without token -> 401
response = client.get("/items")
print(response.status_code)
print(response.json())
# With token -> 200
response = client.get("/items", headers={"Authorization": "Bearer my-secret-token"})
print(response.status_code)
print(response.json())
- •OAuth2PasswordBearer extracts the Bearer token string from the Authorization header
- •tokenUrl tells Swagger UI where to send credentials -- it does not create the endpoint
- •Returns 401 Unauthorized automatically if no token is provided
- •The token is returned as a raw string -- you must validate/decode it yourself
- •tokenUrl is relative to the app root, not an absolute URL -- use 'token' not 'http://localhost/token'
- •OAuth2PasswordBearer does NOT validate the token -- it only extracts it from the header
- •If you use auto_error=False, it returns None instead of raising 401 when the token is missing