0Pricing
FastAPI Backend Development Bootcamp · Lesson

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 /token endpoint.
  • 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.

  • tokenUrl is 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

  1. OAuth2 Password Flow and Token Issuance
  2. Signing and Verifying JWTs with python-jose
  3. Refresh Tokens and Token Rotation
  4. Scope-Based Authorization and Role Guards
← Back to FastAPI Backend Development Bootcamp