FastAPI Users

15.0.5 · maintenance · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart sets up a basic FastAPI application with user registration, login (using JWT stored in a cookie), and user management endpoints. It uses an in-memory SQLite database with SQLAlchemy for simplicity. Remember to replace the `SECRET` with a strong, environment-variable-managed secret in production.

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"],
)

view raw JSON →