FastAPI Users
FastAPI Users provides ready-to-use and customizable user management for FastAPI applications, including authentication, registration, password reset, and OAuth. It reached maintenance mode with version 15.0.0, meaning it will continue to receive security updates and dependency maintenance but no new features. The current version is 15.0.5.
Warnings
- gotcha FastAPI Users entered maintenance mode starting with v15.0.0. While security updates and dependency maintenance will continue, no new features are planned. Consider this for long-term project planning.
- breaking Python 3.9 and Pydantic v1 support was dropped in v15.0.0. Applications targeting these versions must either upgrade their Python/Pydantic or remain on FastAPI Users v14.x.
- breaking A CSRF vulnerability fix in v15.0.2 introduced a cookie requirement for OAuth2 flows. This might require additional configuration for cross-domain setups or if the client isn't sending cookies correctly.
- breaking The underlying password hashing library changed from `passlib` to `pwdlib` in v13.0.0. This is a breaking change only if you were using a custom `CryptContext` configuration.
- gotcha The `fastapi-users` core package only provides the framework. You MUST install a specific database backend (e.g., `fastapi-users[sqlalchemy]`, `fastapi-users[mongodb]`) for persistence.
Install
-
pip install fastapi-users[sqlalchemy] -
pip install fastapi-users[mongodb] -
pip install fastapi-users
Imports
- FastAPIUsers
from fastapi_users import FastAPIUsers
- SQLAlchemyUserDatabase
from fastapi_users_db_sqlalchemy import SQLAlchemyUserDatabase
- BearerBackend
from fastapi_users.authentication import BearerBackend
- CookieBackend
from fastapi_users.authentication import CookieBackend
- AuthenticationBackend
from fastapi_users.authentication import AuthenticationBackend
- UUIDIDStrategy
from fastapi_users.authentication import JWTStrategy, Strategy, UUIDIDStrategy
Quickstart
import uuid
from typing import AsyncGenerator
from fastapi import Depends, FastAPI
from fastapi_users import FastAPIUsers, schemas
from fastapi_users.authentication import JWTStrategy, AuthenticationBackend, CookieBackend
from fastapi_users_db_sqlalchemy import SQLAlchemyUserDatabase, UUID_ID, SQLAlchemyBaseUserTableUUID
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, DeclarativeBase
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
SECRET = "" # For JWT and Cookie backend, replace with os.environ.get('SECRET', '')
class Base(DeclarativeBase):
pass
class User(SQLAlchemyBaseUserTableUUID, Base):
pass
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async_engine = create_async_engine(DATABASE_URL)
async_session_maker = sessionmaker(async_engine, class_=AsyncSession, expire_on_commit=False)
async with async_session_maker() as session:
yield session
async def create_db_and_tables():
async_engine = create_async_engine(DATABASE_URL)
async with async_engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
yield SQLAlchemyUserDatabase(session, User)
def get_jwt_strategy() -> JWTStrategy[User, UUID_ID]:
return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
auth_backend = AuthenticationBackend(
name="jwt",
transport=CookieBackend(name="b", lifetime_seconds=3600, secret=SECRET),
get_strategy=get_jwt_strategy,
)
fastapi_users = FastAPIUsers[User, UUID_ID](
get_user_db,
[auth_backend],
)
app = FastAPI()
@app.on_event("startup")
async def on_startup():
await create_db_and_tables()
app.include_router(
fastapi_users.get_auth_router(auth_backend),
prefix="/auth/jwt",
tags=["auth"],
)
app.include_router(
fastapi_users.get_register_router(),
prefix="/auth",
tags=["auth"],
)
app.include_router(
fastapi_users.get_users_router(),
prefix="/users",
tags=["users"],
)