FastAPI Integration¶
FastAPI is built on Starlette, so NeoZen's Starlette adapter (neozen.ext.starlette) works in a FastAPI app as it is. There is no FastAPI package: the dependencies below are all it takes, and they are yours to change. Coming from FastAPI Users? See the migration guide.
Setup and Dependencies¶
auth.py holds the backend, and a dependency for each question a route asks: who is signed in, how recently, with which role or permission.
from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import Annotated
from fastapi import Depends, HTTPException, Request
from pwdlib import PasswordHash
from pwdlib.hashers.argon2 import Argon2Hasher
from pwdlib.hashers.bcrypt import BcryptHasher
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
from neozen.ext.starlette import NeoZenBackend, get_backend, get_current_user
from neozen.storage.sqlalchemy import (
RoleServiceFactory,
SessionServiceFactory,
create_subject_loader,
)
from neozen.storage.sqlalchemy.models import Subject
from neozen.web.auth.backend import FRESH_LOGIN_MAX_AGE, signed_in_within
from neozen.web.auth.permissions import holds_any_role, missing_permission
SECRET_KEY = "change-me-in-production"
engine = create_async_engine("sqlite+aiosqlite:///./app.db")
session_factory = async_sessionmaker(engine, expire_on_commit=False)
hasher = PasswordHash((Argon2Hasher(), BcryptHasher()))
backend = NeoZenBackend(
session_service=SessionServiceFactory(session_factory, SECRET_KEY),
subject_loader=create_subject_loader(session_factory),
role_service=RoleServiceFactory(session_factory),
)
async def signed_in(request: Request) -> Subject:
"""The signed-in subject, or a 401."""
subject = await get_current_user(request)
if subject is None:
raise HTTPException(401, "Authentication required")
return subject
CurrentUser = Annotated[Subject, Depends(signed_in)]
async def freshly_signed_in(request: Request, user: CurrentUser) -> Subject:
"""The same, if they signed in recently."""
if not signed_in_within(request.state.neozen_session, FRESH_LOGIN_MAX_AGE):
raise HTTPException(401, "Sign in again")
return user
FreshUser = Annotated[Subject, Depends(freshly_signed_in)]
def has_role(*roles: str) -> Callable[..., Awaitable[Subject]]:
"""A dependency: a subject with one of these roles, or a 403."""
async def check(request: Request, user: CurrentUser) -> Subject:
held = await get_backend(request).subject_roles(request.state.neozen_session)
if not holds_any_role(held, user, roles):
raise HTTPException(403, "Insufficient permissions")
return user
return check
def may(*permissions: str) -> Callable[..., Awaitable[Subject]]:
"""A dependency: a subject with all of these permissions, or a 403."""
async def check(request: Request, user: CurrentUser) -> Subject:
held = await get_backend(request).subject_roles(request.state.neozen_session)
if missing := missing_permission(held, user, permissions):
raise HTTPException(403, f"Missing permission: {missing}")
return user
return check
PasswordHash lists bcrypt after Argon2id so that older bcrypt hashes still verify; a new app can use PasswordHash.recommended(). Create the tables with neozen db upgrade, or run_neozen_migrations in your Alembic env.py.
The session cookie is Secure: over plain HTTP in development, pass cookie_secure=False to NeoZenBackend.
Routes¶
from __future__ import annotations
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Request, Response
from pydantic import BaseModel
from auth import (
CurrentUser,
FreshUser,
backend,
has_role,
hasher,
may,
session_factory,
)
from neozen.core.factors.password import InvalidCredentialsError, create_password_factor
from neozen.core.identifiers.email import create_email_identifier
from neozen.ext.starlette import (
NeoZenMiddleware,
login_required,
login_user,
logout_other_sessions,
logout_user,
)
from neozen.storage.sqlalchemy import SubjectRepository
from neozen.storage.sqlalchemy.models import Subject
app = FastAPI()
app.add_middleware(NeoZenMiddleware, backend=backend)
class Credentials(BaseModel):
email: str
password: str
@app.post("/login")
async def login(
credentials: Credentials, request: Request, response: Response
) -> dict[str, str]:
async with session_factory() as db:
subjects = SubjectRepository(session=db)
factor = create_password_factor(
create_email_identifier(subjects), subjects, hasher
)
try:
subject = await factor.authenticate({
"identifier": credentials.email,
"password": credentials.password,
})
except InvalidCredentialsError:
raise HTTPException(401, "Invalid email or password") from None
await db.commit() # a bcrypt hash was rewritten as Argon2id
await login_user(request, response, subject)
return {"id": subject.id}
@app.post("/logout", status_code=204)
async def logout(request: Request, response: Response) -> None:
await logout_user(request, response)
@app.get("/me")
async def me(user: CurrentUser) -> dict[str, str]:
return {"id": user.id, "email": user.email}
@app.get("/admin", dependencies=[Depends(has_role("admin"))])
async def admin() -> dict[str, str]:
return {"admin": "yes"}
@app.delete("/posts/{post_id}", status_code=204)
async def delete_post(
post_id: int, user: Annotated[Subject, Depends(may("post:delete"))]
) -> None: ...
@app.post("/logout-others")
async def logout_others(request: Request, _user: FreshUser) -> dict[str, int]:
return {"ended": await logout_other_sessions(request)}
login_user sets the cookie on the Response FastAPI injects. If a handler returns a response of its own (a RedirectResponse), pass that one instead: FastAPI drops the cookies of the injected one.
Signing out revokes the session on the server, so a copied cookie stops working too. logout_other_sessions is what to call after a password change.
The Starlette decorators (login_required, fresh_login_required, roles_required, permissions_required) work on FastAPI handlers too, if the handler takes request: Request. Dependencies are the better fit in FastAPI: they give the handler the user, and apply to a whole router with APIRouter(dependencies=[...]).
Bearer Tokens¶
NeoZenMiddleware reads the cookie only. For API clients, create the session yourself, return its token, and read it back in a dependency:
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
bearer = HTTPBearer()
async def token_subject(
credentials: Annotated[HTTPAuthorizationCredentials, Depends(bearer)],
) -> Subject:
session = await backend.get_session(credentials.credentials)
subject = session and await backend.get_subject(session.subject_id)
if subject is None:
raise HTTPException(401, "Invalid token")
return subject
@app.post("/api/login")
async def api_login(credentials: Credentials) -> dict[str, str]:
subject = await authenticate(credentials) # as in /login above
return {"token": await backend.create_session(subject.id)}
The tokens are opaque and checked in the database on each request, so revoking one takes effect at once.
Login Throttling¶
SignInAttempt counts attempts per address and per account. Wrap the password check in it:
from neozen.core.security import InMemoryRateLimitStore, RateLimitConfig, RateLimiter
from neozen.ext.starlette import get_client_ip
from neozen.web.rate_limit import SignInAttempt
limiter = RateLimiter(RateLimitConfig(max_attempts=5), InMemoryRateLimitStore())
@app.post("/login")
async def login(
credentials: Credentials, request: Request, response: Response
) -> dict[str, str]:
attempt = SignInAttempt.start(limiter, get_client_ip(request), credentials.email)
if not (await attempt.check()).allowed:
raise HTTPException(429, "Too many attempts")
... # then, once the password is checked:
await attempt.record(success=True) # or False
The in-memory store counts per process: with several workers, use SQLAlchemyRateLimitStore(session_factory).
OAuth Server Routes¶
Mount the OpenID Connect provider's routes as a Starlette app:
from starlette.applications import Starlette
app.mount("/oauth", Starlette(routes=create_oauth_routes(...)))
They don't appear in FastAPI's OpenAPI schema.
CSRF Protection¶
NeoZen's session cookie is SameSite=Lax, which stops most cross-site form posts but not all of them (older browsers, SameSite=None deployments). FastAPI has no CSRF protection of its own: if your app posts HTML forms, add a middleware such as starlette-csrf. The OAuth consent form protects itself (Consent Form).