CIRCLE
Getting started

Quick start

A FastAPI backend with sign-in, a session and a protected route in about fifty lines.

This page builds the smallest working backend: sign-in, session cookie, /auth/me and one protected route. It uses in-memory stores, which are only fit for a demo or a single instance: see Production checklist before deploying.

Prerequisites

  • The SDK installed with the fastapi extra, and an ASGI server such as uvicorn.
  • An application registered in auth-service with the redirect URI https://app.example.com/auth/callback, the post-logout redirect URI https://app.example.com/auth/logout/callback, and a back-channel logout URI https://app.example.com/auth/backchannel-logout.
  • Three values in your environment: AUTH_ISSUER (the auth-service URL), AUTH_CLIENT_SECRET and AUTH_COOKIE_SECRET (at least 32 random characters, for example openssl rand -base64 48).

The server

main.py
import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from typing import Annotated

from fastapi import Depends, FastAPI

from auth_ai import AuthClient, GrantManager, MemoryGrantStore
from auth_ai.starlette import install_auth, require_auth
from auth_ai.web import AuthHandlers, MemorySessionStore, Session


def env(name: str) -> str:
    # A missing secret must stop the process: without a client secret the SDK
    # would silently act as a public client.
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Missing environment variable {name}")
    return value


auth = AuthClient(
    {
        "issuer": env("AUTH_ISSUER"),
        "client_id": "my-app",
        "client_secret": env("AUTH_CLIENT_SECRET"),
        "redirect_uri": "https://app.example.com/auth/callback",
        "post_logout_redirect_uri": "https://app.example.com/auth/logout/callback",
    }
)
grants = GrantManager(auth=auth, store=MemoryGrantStore())
handlers = AuthHandlers(
    auth=auth,
    grants=grants,
    sessions=MemorySessionStore(),
    secret=env("AUTH_COOKIE_SECRET"),
)


@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
    yield
    await auth.aclose()


app = FastAPI(lifespan=lifespan)
install_auth(app, handlers)

current_session = require_auth(handlers)


@app.get("/api/profile")
async def profile(session: Annotated[Session, Depends(current_session)]) -> dict[str, object]:
    return {"sub": session.claims.sub, "roles": session.claims.roles or []}

Run it with uvicorn main:app --port 3000.

AuthClient accepts either an AuthClientConfig or a plain mapping, and validates it when it is created: any invalid value (a trailing slash on issuer, a non-HTTPS URL, a missing openid scope…) raises an AuthAiError with the code CFG_001. AuthHandlers also checks that the path of redirect_uri is <base_path>/callback; base_path defaults to /auth. Set post_logout_redirect_uri to the absolute URL <origin><base_path>/logout/callback (for example https://app.example.com/auth/logout/callback) so the provider returns to the route the SDK serves. The client owns an httpx2.AsyncClient, so close it with await auth.aclose() (or use async with AuthClient(...)) when the application stops.

What you get

install_auth serves six routes below /auth and makes an AuthAiError raised in your own routes answer with the public error envelope:

RouteMethodWhat it does
/auth/loginGETRedirects to auth-service. Accepts ?next=/path (same-origin paths only) and ?prompt=.
/auth/callbackGETCompletes the sign-in, creates the session and redirects to next.
/auth/meGETReturns { "user": …, "expiresAt": … }, or 401 with SES_001 when signed out.
/auth/logoutPOSTEnds the session, then redirects (303) to the provider's logout URL, or answers { "logoutUrl": … } when the request sends Accept: application/json.
/auth/logout/callbackGETThe post-logout landing route: clears the sealed logout cookie and 303s to the requested next path. Register its absolute URL as the application's post_logout_redirect_uri.
/auth/backchannel-logoutPOSTCalled by auth-service to end sessions.

Open https://app.example.com/auth/login?next=/api/profile in a browser: you are sent to auth-service, sign in, and land on /api/profile with a session cookie. The cookie is HttpOnly, Secure, SameSite=Lax and prefixed with __Host- on HTTPS; the browser never sees a token. A signed-out request to /api/profile gets 401 and {"error": {"code": "SES_001", "message": "Not signed in"}}.

Local development works over plain HTTP on loopback: redirect_uri may be http://localhost:3000/auth/callback (and only for localhost, 127.0.0.1 or ::1). The cookies then lose the Secure flag and the __Host- prefix.

Where to go next

Copyright © 2026