Backends, Registration & Protecting Routes
Boilerplate FastAPI Users Removes
FastAPI Users is a ready-made authentication/user-management library for FastAPI apps — registration, login, password reset, and email verification are common, largely boilerplate flows across many APIs, and this library packages them as reusable, mountable components rather than requiring each project to rebuild them from scratch. It's database-agnostic via adapters (SQLAlchemy, Beanie for MongoDB, Tortoise ORM), plugging into whatever ORM the app already uses.
Auth Backends: Transport + Strategy
A "backend" separates transport (how the token travels — an HTTP-only cookie or an Authorization header) from strategy (how it's generated/validated — JWT, or a database-backed session). JWT is stateless and avoids a database lookup per request, at the cost of harder immediate revocation; a database-backed session is trivially revocable but costs a lookup per request — a classic tradeoff to pick deliberately.
Mounting the Routers
app.include_router(
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
)
app.include_router(
fastapi_users.get_register_router(UserRead, UserCreate), prefix="/auth", tags=["auth"]
)Pre-built router groups mount onto the app like any other FastAPI router. Registration validates input via a Pydantic schema, hashes the password (a one-way hash means even a database breach doesn't directly expose usable plaintext credentials), and creates the user record.
Protecting Routes via Dependencies
@app.get("/protected")
def protected_route(user: User = Depends(current_active_user)):
return {"email": user.email}
@app.get("/admin")
def admin_route(user: User = Depends(current_superuser)):
return {"ok": True}current_active_user resolves the authenticated user via FastAPI's dependency injection and additionally checks the account is active (not deactivated) — a stronger check than plain authentication alone. current_superuser gates admin-only routes by checking the model's is_superuser flag, reusable across any route needing that restriction.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free