The user posts credentials to a token endpoint; the server verifies the hashed password and returns a signed JWT with an expiry; clients send it as a Bearer token, and a dependency decodes it and loads the current user.
Keep the secret key in the environment, use short expiry times, hash passwords, and always send tokens over HTTPS.
import os
from datetime import datetime, timedelta, timezone
from typing import Annotated
import jwt # PyJWT
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
app = FastAPI()
SECRET_KEY = os.environ["SECRET_KEY"]
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(sub: str, minutes: int = 30) -> str:
exp = datetime.now(timezone.utc) + timedelta(minutes=minutes)
return jwt.encode({"sub": sub, "exp": exp}, SECRET_KEY, algorithm="HS256")
@app.post("/token")
def login(form: Annotated[OAuth2PasswordRequestForm, Depends()]):
user = authenticate(form.username, form.password) # verifies a hashed password
if not user:
raise HTTPException(status_code=401, detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"})
return {"access_token": create_access_token(user.username), "token_type": "bearer"}
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
except jwt.PyJWTError:
raise HTTPException(status_code=401, detail="Invalid or expired token",
headers={"WWW-Authenticate": "Bearer"})
return get_user(payload["sub"])
@app.get("/me")
def me(user: Annotated[User, Depends(get_current_user)]):
return {"username": user.username}