Security model
Built in
| Protection | How |
|---|---|
| Tokens stay on the server | The browser holds an opaque session cookie. SessionUser and /auth/me carry no token, no sid and no timestamps. |
| Hardened cookies | HttpOnly, Secure, SameSite=Lax, Path=/, and the __Host- prefix on HTTPS so a cookie cannot be set from a sibling subdomain. Lax is required: the provider returns to /auth/callback with a top-level GET. Over http://localhost the Secure flag and the prefix are dropped. |
| Session ids are hashed | The store key is the SHA-256 of the cookie value, so a leaked store cannot be replayed as cookies. |
| Sealed handshake | state, nonce, the PKCE verifier and next travel in an AES-256-GCM encrypted cookie that expires after 10 minutes. A tampered, expired or foreign cookie is refused. |
PKCE, state and nonce | Always on; the ID token's nonce is checked again after verification. The state is compared in constant time, and a repeated query parameter, an iss that differs from the provider's issuer, or a missing iss when the provider advertises one is refused. |
| Verified tokens | Signatures are checked against the provider's JWKS with the asymmetric algorithms the provider declares. none and HMAC never qualify. Issuer, audience and expiry are checked, with clock_tolerance_seconds (5 by default). |
| Same-origin redirects | next is reduced to a path on your origin. Absolute URLs, //host, backslashes and control characters fall back to default_redirect. |
| URLs on the registered origin | The callback URL is rebuilt from redirect_uri, and the Starlette adapter builds the WebRequest on that origin: the Host header is never trusted. |
| Cross-site logout refused | POST /auth/logout answers 403 SES_004 when Origin differs from your origin or Sec-Fetch-Site is neither same-origin nor none. Requests without either header (non-browser clients) carry no ambient cookie and pass. |
| Logout tokens | The back-channel handler requires a logout+jwt with the logout event, a jti, a sid and a sub, no nonce, a lifetime of at most 600 seconds, and claims each jti once. |
| No leaking gateway token | GatewayAuth refuses any origin other than the gateway's, so the user's token cannot be sent elsewhere. The wallet, machine and gateway calls do not follow HTTP redirects. |
| Bearer verification | Only JWT access tokens whose aud contains your audience are accepted. Opaque tokens are refused. |
| Secrets stay out of reprs | TokenSet, AccessToken and LoginHandshake hide their secrets from repr, and the client secret is a pydantic SecretStr, so logging them leaks nothing. |
Error policy
Every failure is an AuthAiError with a stable code.
messageanddetailscarry what a developer needs (a provider's description, a missing scope) and belong in your logs.to_public_json()returns only the code and the registry's generic message. Every HTTP response uses it, in the same{ "error": { "code", "message" } }envelope as auth-service. Do the same in your own routes.to_json()includesmessageanddetails: use it for logging, never in a response.
import logging
from auth_ai import AuthAiError
logger = logging.getLogger(__name__)
def log_and_answer(err: AuthAiError) -> dict[str, object]:
logger.warning("auth error", extra={"error": err.to_json()}) # detailed: for operators
return {"error": err.to_public_json()} # generic: for the user
One answer for every sign-in failure
Whatever fails in /auth/callback (a forged state, a rejected code, a wrong client secret, a missing sid, an error=access_denied from the provider), the browser gets the same 403 with SES_005 "Sign-in failed", or a redirect to error_redirect?error=SES_005. Telling a rejected client secret from a forged state would only help whoever probes the callback. The real cause reaches on_error.
Your responsibility
- Secrets from the environment. The SDK reads none: it takes the client secret and the cookie secret as parameters. Never commit them. The cookie secret must be at least 32 characters, and random (
CFG_001otherwise). - Your own state-changing routes. The SDK enforces the same-origin rule on logout only. Apply an
Origincheck to your otherPOST,PUT,PATCHandDELETEroutes, as the FastAPI guide does. - Logs. The callback URL carries the authorization code in its query string: do not log query strings. See the production checklist.
- Back-channel route. The endpoint is called by auth-service without cookies or credentials: keep it outside any session or CSRF protection, and reachable over HTTPS.
- Stores. The in-memory stores are for demos and one process. Encrypt refresh tokens at rest in your own
GrantStore.
To report a vulnerability in the SDK, see SECURITY.md.
Credit wallet and LiteLLM gateway
How gateway_url, the wallet scope and the per-audience tokens let users call LLMs against their prepaid credit, and why the SDK has no debit API.
FastAPI backend
A complete backend-for-frontend on FastAPI: sign-in, sessions, safe logging, same-origin protection, gateway and billing routes.