Implement the stores
The in-memory stores (MemorySessionStore, MemoryGrantStore, InProcessGrantLock, MemoryReplayStore) are for demos, tests and a single instance: a restart signs everyone out, and replicas cannot share them. In production, implement the protocols on your application's database.
The four contracts are typing.Protocol classes: your class does not inherit from anything, it only needs the same async methods.
| Protocol | Holds | Shared across replicas? |
|---|---|---|
SessionStore | Browser sessions: claims and ID token. | Yes, required. |
GrantStore | One refresh token per user. | Yes, required. |
GrantLock | Mutual exclusion of refreshes per grant. | Yes, with several replicas. |
ReplayStore | The jti of accepted logout tokens. | Yes, with several replicas. |
SessionStore
From auth_ai.web. Records are keyed by Session.id, which is already the SHA-256 of the cookie value: store it as is. Index user_id and session_id.
| Method | Contract |
|---|---|
create(session) | Inserts the session. |
get(session_key) | Returns the session, or None for an unknown or expired one (expires_at, in Unix seconds, is in the past). |
update(session) | Replaces an existing session (the claims renewal). Do nothing if it no longer exists, so a renewal never resurrects a session that was ended meanwhile. |
delete(session_key) | Removes the session. Idempotent. |
delete_by_provider_session(session_id) | Removes every session whose session_id equals the argument and returns what was removed. Back-channel logout relies on the returned list to revoke grants. |
count_by_user(user_id) | Number of non-expired sessions of the user. The grant is revoked when it reaches zero after a sign-out. |
Session is a frozen dataclass with id, user_id, session_id (the provider session, str | None), claims (an IdTokenClaims), id_token, created_at, expires_at and renew_at (all Unix seconds). It holds claims and id_token: treat them as sensitive. Purge expired rows periodically.
GrantStore
From auth_ai. The provider rotates the refresh token on every use, so a store holds exactly one value per grant.
| Method | Contract |
|---|---|
get(grant_id) | The refresh token, or None. |
set(grant_id, refresh_token) | Inserts or overwrites. |
delete(grant_id) | Removes the grant. Idempotent. |
The refresh token is a long-lived credential: encrypt it at rest (for example AES-256-GCM with a key from your secret manager).
GrantLock
hold(grant_id) returns an async context manager. It must let one holder at a time into the block for a given grant, and release the lock when the block exits, including on an exception. Holders of different grants may run in parallel. The default, InProcessGrantLock, only covers one process. An @asynccontextmanager function is the easiest way to write one.
ReplayStore
From auth_ai.server. claim(jti, expires_at) must be atomic: True the first time a jti is seen, False afterwards, until expires_at (Unix seconds, a float). Pass your store to AuthHandlers(replay_store=...).
SQLAlchemy sketch
The models and the session store, on SQLAlchemy 2 async. The JSON column holds the claims; use JSONB on PostgreSQL.
import time
from collections.abc import Sequence
from typing import Any
from sqlalchemy import JSON, BigInteger, String, Text, delete, func, select, update
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from auth_ai import IdTokenClaims
from auth_ai.web import Session
class Base(DeclarativeBase):
pass
class SessionRow(Base):
__tablename__ = "auth_sessions"
id: Mapped[str] = mapped_column(String, primary_key=True) # SHA-256 of the cookie, from the SDK
user_id: Mapped[str] = mapped_column(String, index=True)
provider_session_id: Mapped[str | None] = mapped_column(String, index=True)
claims: Mapped[dict[str, Any]] = mapped_column(JSON)
id_token: Mapped[str] = mapped_column(Text)
created_at: Mapped[int] = mapped_column(BigInteger)
expires_at: Mapped[int] = mapped_column(BigInteger)
renew_at: Mapped[int] = mapped_column(BigInteger)
class GrantRow(Base):
__tablename__ = "auth_grants"
grant_id: Mapped[str] = mapped_column(String, primary_key=True)
refresh_token: Mapped[str] = mapped_column(Text) # encrypted
def to_row(session: Session) -> SessionRow:
return SessionRow(
id=session.id,
user_id=session.user_id,
provider_session_id=session.session_id,
claims=session.claims.model_dump(mode="json"),
id_token=session.id_token,
created_at=session.created_at,
expires_at=session.expires_at,
renew_at=session.renew_at,
)
def to_session(row: SessionRow) -> Session:
return Session(
id=row.id,
user_id=row.user_id,
session_id=row.provider_session_id,
claims=IdTokenClaims.model_validate(row.claims),
id_token=row.id_token,
created_at=row.created_at,
expires_at=row.expires_at,
renew_at=row.renew_at,
)
class DbSessionStore:
def __init__(self, maker: async_sessionmaker[AsyncSession]) -> None:
self._maker = maker
async def create(self, session: Session) -> None:
async with self._maker.begin() as db:
db.add(to_row(session))
async def get(self, session_key: str) -> Session | None:
async with self._maker() as db:
row = await db.scalar(
select(SessionRow).where(
SessionRow.id == session_key, SessionRow.expires_at > int(time.time())
)
)
return to_session(row) if row else None
async def update(self, session: Session) -> None:
# Updates an existing row only: never resurrects an ended session.
values = to_row(session)
async with self._maker.begin() as db:
await db.execute(
update(SessionRow)
.where(SessionRow.id == session.id)
.values(
claims=values.claims,
id_token=values.id_token,
expires_at=values.expires_at,
renew_at=values.renew_at,
)
)
async def delete(self, session_key: str) -> None:
async with self._maker.begin() as db:
await db.execute(delete(SessionRow).where(SessionRow.id == session_key))
async def delete_by_provider_session(self, session_id: str) -> Sequence[Session]:
async with self._maker.begin() as db:
result = await db.execute(
delete(SessionRow)
.where(SessionRow.provider_session_id == session_id)
.returning(SessionRow)
)
return [to_session(row) for row in result.scalars()]
async def count_by_user(self, user_id: str) -> int:
async with self._maker() as db:
count = await db.scalar(
select(func.count())
.select_from(SessionRow)
.where(SessionRow.user_id == user_id, SessionRow.expires_at > int(time.time()))
)
return count or 0
The grant store encrypts the refresh token with AES-256-GCM and binds the ciphertext to its grant id. cryptography is installed with the SDK (it is a dependency of joserfc), but declare it in your own dependencies when you import it.
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from sqlalchemy import select, delete
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from auth_stores import GrantRow
def encrypt(key: bytes, grant_id: str, plaintext: str) -> str:
nonce = os.urandom(12)
sealed = AESGCM(key).encrypt(nonce, plaintext.encode(), grant_id.encode())
return base64.urlsafe_b64encode(nonce + sealed).decode()
def decrypt(key: bytes, grant_id: str, value: str) -> str:
raw = base64.urlsafe_b64decode(value)
return AESGCM(key).decrypt(raw[:12], raw[12:], grant_id.encode()).decode()
class DbGrantStore:
def __init__(self, maker: async_sessionmaker[AsyncSession], key: bytes) -> None:
# `key` is 32 bytes from your secret manager.
self._maker = maker
self._key = key
async def get(self, grant_id: str) -> str | None:
async with self._maker() as db:
row = await db.scalar(select(GrantRow).where(GrantRow.grant_id == grant_id))
return decrypt(self._key, grant_id, row.refresh_token) if row else None
async def set(self, grant_id: str, refresh_token: str) -> None:
encrypted = encrypt(self._key, grant_id, refresh_token)
async with self._maker.begin() as db:
await db.merge(GrantRow(grant_id=grant_id, refresh_token=encrypted))
async def delete(self, grant_id: str) -> None:
async with self._maker.begin() as db:
await db.execute(delete(GrantRow).where(GrantRow.grant_id == grant_id))
Locks and replay store
GrantLock across replicas, with a PostgreSQL advisory lock held for the duration of the block, or with a Redis lock:
import math
import time
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from redis.asyncio import Redis
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
class PgGrantLock:
"""One refresh at a time per grant, across replicas. Each holder keeps one connection."""
def __init__(self, maker: async_sessionmaker[AsyncSession]) -> None:
self._maker = maker
@asynccontextmanager
async def hold(self, grant_id: str) -> AsyncIterator[None]:
async with self._maker.begin() as db:
await db.execute(
text("select pg_advisory_xact_lock(hashtext(:grant_id))"), {"grant_id": grant_id}
)
yield
class RedisGrantLock:
def __init__(self, redis: Redis, *, timeout_seconds: float = 30.0) -> None:
self._redis = redis
self._timeout = timeout_seconds
@asynccontextmanager
async def hold(self, grant_id: str) -> AsyncIterator[None]:
# The lock expires on its own if the process dies while holding it.
async with self._redis.lock(f"auth-ai:grant:{grant_id}", timeout=self._timeout):
yield
class RedisReplayStore:
def __init__(self, redis: Redis) -> None:
self._redis = redis
async def claim(self, jti: str, expires_at: float) -> bool:
ttl_ms = max(1, math.ceil((expires_at - time.time()) * 1000))
# SET ... NX only succeeds for the first caller.
return bool(await self._redis.set(f"logout-jti:{jti}", "1", px=ttl_ms, nx=True))
Wire them together:
from redis.asyncio import Redis
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from auth_ai import AuthClient, GrantManager
from auth_ai.web import AuthHandlers
from auth_grants import DbGrantStore
from auth_locks import PgGrantLock, RedisReplayStore
from auth_stores import DbSessionStore
def build_handlers(
auth: AuthClient,
maker: async_sessionmaker[AsyncSession],
redis: Redis,
encryption_key: bytes,
cookie_secret: str,
) -> AuthHandlers:
grants = GrantManager(
auth=auth,
store=DbGrantStore(maker, encryption_key),
lock=PgGrantLock(maker),
)
return AuthHandlers(
auth=auth,
grants=grants,
sessions=DbSessionStore(maker),
replay_store=RedisReplayStore(redis),
secret=cookie_secret,
)
GrantManager stays in each process: that is by design, since access tokens are never persisted. Each replica mints its own, serialised by the shared lock.Protect an API
Verify auth-service bearer tokens on your own API, require scopes, and publish protected-resource metadata so MCP and OAuth clients can find the provider.
Use the TypeScript client
Pair the Python backend with the browser client and the React and Vue bindings of @circle-rd/auth-ai, which are documented in the TypeScript SDK site.