OAuth2 with JWT in Python
From the FastAPI cheat sheet · Security & Authentication · verified Jul 2026
OAuth2 with JWT
Implement token-based authentication with password hashing.
python
from fastapi import Depends
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form: OAuth2PasswordRequestForm = Depends()):
user = authenticate(form.username, form.password)
token = create_access_token({"sub": user.username})
return {"access_token": token, "token_type": "bearer"}💡 OAuth2PasswordBearer auto-adds a login button to the /docs UI
⚡ Install dependencies: pip install python-jose[cryptography] passlib[bcrypt]
📌 Never store plain-text passwords — always hash with bcrypt via passlib
🟢 Chain dependencies: protected routes just add user = Depends(get_current_user)
authjwtoauth2security