OAuth2 Password Flow and Token Issuance
Implement the OAuth2PasswordBearer scheme, hash passwords with passlib, and issue signed access tokens on login.
The OAuth2 Password Flow in Plain English
The OAuth2 password flow (a.k.a. the Resource Owner Password Credentials grant) is the simplest way to authenticate a first-party client: the user sends their username and password directly to your API, and the API hands back a signed access token.
- The client posts credentials once to a
/tokenendpoint. - The server verifies them against the database.
- On success it returns a short-lived JWT access token.
- Every later request carries that token in the
Authorization: Bearer <token>header.
FastAPI gives us ready-made building blocks for exactly this: OAuth2PasswordBearer and OAuth2PasswordRequestForm.
Declaring the OAuth2PasswordBearer Scheme
OAuth2PasswordBearer is a FastAPI dependency that knows how to pull a bearer token out of the Authorization header. You create one instance and point its tokenUrl at the login endpoint that issues tokens.
tokenUrlis a relative path — it tells the docs UI where clients should request a token.- Using the scheme as a dependency makes the endpoint require a token; a missing or malformed header returns 401 automatically.
from fastapi import Depends, FastAPI
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
# 'token' matches the path of our login route below
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
async def read_me(token: str = Depends(oauth2_scheme)):
# FastAPI extracts the raw bearer token string for us
return {"token": token}All lessons in this course
- OAuth2 Password Flow and Token Issuance
- Signing and Verifying JWTs with python-jose
- Refresh Tokens and Token Rotation
- Scope-Based Authorization and Role Guards