📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI FastAPI OAuth2

FastAPI OAuth2

6 min read Quiz at the end
OAuth2 password flow: /token endpoint, JWT encoding, and get_current_user dependency.

OAuth2 Password Flow

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import jwt
from passlib.context import CryptContext

pwd_context   = CryptContext(schemes=["bcrypt"])
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")

@app.post("/token")
async def login(form: OAuth2PasswordRequestForm = Depends(), db = Depends(get_db)):
    user = authenticate_user(db, form.username, form.password)
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    token = jwt.encode({"sub": str(user.id)}, SECRET_KEY, ALGORITHM)
    return {"access_token": token, "token_type": "bearer"}