OAuth2 & JWT

How Token Login Works

  1. The client sends username and password to POST /token (form data).
  2. The server checks them and returns a signed JWT access token with an expiry.
  3. The client sends Authorization: Bearer <token> with every request.
  4. Protected endpoints verify the token's signature and expiry with a dependency.

Complete Example

Example

Login, then call a protected endpoint with and without the token:

from datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm

SECRET_KEY = "change-me-to-a-long-random-secret-from-the-environment"
ALGORITHM = "HS256"
USERS = {"asha": {"username": "asha", "password": "S3cret!pass", "role": "student"}}  # demo only: store hashes!

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

def create_token(username: str) -> str:
    expire = datetime.now(timezone.utc) + timedelta(minutes=30)
    return jwt.encode({"sub": username, "exp": expire}, SECRET_KEY, algorithm=ALGORITHM)

@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]):
    user = USERS.get(form.username)
    if not user or user["password"] != form.password:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Incorrect username or password")
    return {"access_token": create_token(user["username"]), "token_type": "bearer"}

def current_user(token: Annotated[str, Depends(oauth2_scheme)]):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except jwt.InvalidTokenError:
        raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid or expired token")
    return USERS[payload["sub"]]

@app.get("/me")
def me(user: Annotated[dict, Depends(current_user)]):
    return {"username": user["username"], "role": user["role"]}

# ---- demo: log in and use the token ----
from fastapi.testclient import TestClient
_c = TestClient(app)
_token = _c.post("/token", data={"username": "asha", "password": "S3cret!pass"}).json()["access_token"]
print("token starts with:", _token[:20] + "...")
print("GET /me with token →", _c.get("/me", headers={"Authorization": f"Bearer {_token}"}).json())

Requests and responses

token starts with: eyJhbGciOiJIUzI1NiIs...
GET /me with token → {'username': 'asha', 'role': 'student'}
POST /token
→ 401 {"detail": "Incorrect username or password"}
GET /me
→ 401 {"detail": "Not authenticated"}
GET /me
→ 401 {"detail": "Invalid or expired token"}

Note: Keep SECRET_KEY in an environment variable or secret manager, use short expiry times, and always serve the API over HTTPS.