Authentication and SecurityLesson 4.3
How to implement OAuth2 password flow login in FastAPI
OAuth2PasswordBearer, OAuth2PasswordRequestForm, token endpoint, login flow, get_current_user dependency, WWW-Authenticate header, bearer token
OAuth2 Password Flow in FastAPI
FastAPI ships with OAuth2PasswordBearer and OAuth2PasswordRequestForm that implement the OAuth2 password grant flow — the standard approach for first-party login forms.
Login endpoint
from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token")
@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form.username, form.password)
if not user:
raise HTTPException(
status_code=401,
detail="Incorrect credentials",
headers={"WWW-Authenticate": "Bearer"}
)
token = create_access_token({"sub": user.email})
return {"access_token": token, "token_type": "bearer"}
Protecting routes
async def get_current_user(token: str = Depends(oauth2_scheme)):
payload = decode_token(token)
email = payload.get("sub")
if not email:
raise HTTPException(401, "Invalid token")
return get_user_by_email(db, email)
@app.get("/me")
def me(user=Depends(get_current_user)):
return user
oauth2_scheme extracts the bearer token from the Authorization header automatically. If the header is missing, it returns a 401. The sub claim by convention holds the user identifier. Any route that depends on get_current_user is now protected.
