CIRCLE
Reference

Server API

Reference of auth_ai.server: bearer token verification, protected-resource metadata, back-channel logout and the machine API for billing and consumption.

Everything below is exported from auth_ai.server. It needs no web framework.

Bearer verification

BearerVerifier(auth, *, audience) verifies JWT access tokens minted for your API. auth is an AuthClient; audience must be a URL (otherwise CFG_001) and must appear in the token's aud. Opaque tokens are refused.

MemberDescription
verify(token) -> VerifiedAccessTokenVerifies a raw JWT: signature, issuer, audience and expiry, then that it is bound to a client (azp). Failures are TOK_001.
verify_header(authorization) -> VerifiedAccessTokenSame, from the value of an Authorization: Bearer … header (str | None). A missing or malformed header raises TOK_003.

Related functions:

FunctionDescription
extract_bearer_token(authorization) -> strReturns the token of a bearer Authorization header, or raises TOK_003.
require_scopes(token, *required)Raises TOK_004 (with details["missing"]) unless the VerifiedAccessToken carries every listed scope.

VerifiedAccessToken is a frozen dataclass:

FieldDescription
user_idThe end user's sub, or None for a client_credentials token (where sub is the client id itself).
client_idThe OAuth client the token was issued to (azp).
scopestuple[str, ...] of the granted scopes.
audiencestuple[str, ...] of the aud values.
claimsThe AccessTokenClaims.

See Protect an API for a complete example.

Protected-resource metadata

FunctionDescription
protected_resource_metadata(auth, *, resource, scopes_supported=None) -> dict[str, object]The RFC 9728 document: resource, authorization_servers (the issuer), bearer_methods_supported (["header"]) and, when given, scopes_supported.
protected_resource_metadata_path(resource) -> strWhere to serve it: /.well-known/oauth-protected-resource followed by the path of resource.
bearer_challenge(resource_metadata_url, *, error=None, scope=None) -> strThe value of the WWW-Authenticate header of a 401 or 403. error is "invalid_token" or "insufficient_scope". Raises CFG_001 for a value containing ", \, CR or LF.

Back-channel logout

BackchannelLogoutHandler(*, auth, on_logout, replay_store=None, on_error=None) handles the endpoint auth-service calls when a user signs out. AuthHandlers mounts one at /backchannel-logout for you; build your own only when you do not use the sign-in handlers.

It is a callable: await handler(request) takes a WebRequest and returns a WebResponse. It is called without cookies or credentials, so mount it outside any session or CSRF protection.

PartDescription
on_logoutCallable[[BackchannelLogoutEvent], Awaitable[None] | None]. Called with a BackchannelLogoutEvent (sid, sub): end every local session whose stored sid equals this one.
replay_storeA ReplayStore, defaulting to MemoryReplayStore(). Share it across replicas.
on_errorReceives every rejected token and failed callback: the response carries no detail.

Answers:

StatusWhen
204The logout token is valid and on_logout succeeded.
400 with {"error": "invalid_request"}The content type is not application/x-www-form-urlencoded, the body is larger than 16 KiB, logout_token is missing, or the token is invalid or replayed.
500 with {"error": "server_error"}on_logout failed.
405 with Allow: POSTAny other method.

verify_logout_token(auth, token, replay_store) -> LogoutTokenClaims is the verifier behind it. It requires a logout+jwt for your client id with the back-channel logout event, a jti, a sid and a sub, no nonce, a lifetime of at most 600 seconds and an iat not in the future, and claims the jti once. Failures are TOK_001. LogoutTokenClaims has sid, sub, jti, iat and exp.

ReplayStore is a protocol with one method, claim(jti, expires_at) -> bool: True the first time, False on a replay. See Implement the stores.

MachineApi

MachineApi(auth) calls the auth-service REST API as your application, with client_credentials tokens minted from its own secret. It raises CFG_001 without a client_secret. The scopes billing:read, consumption:read and consumption:write must be granted to the application by a superadmin; a refused scope raises TOK_004 with details["scope"].

It has two members, billing and consumption. See Billing and consumption.

machine.billing

MethodReturnsDescription
get_subscription(user_id)SubscriptionView | NoneNone when the user has no subscription. Fields: plan (id, name), is_active, expires_at, stripe_status, current_period_start, current_period_end, cancel_at_period_end, canceled_at.
get_usage(user_id)UsageViewperiod_start and features: each has feature_key, unit, usage_limit (-1 is unlimited), used and remaining (None when unlimited).
list_invoices(user_id, *, limit=None, cursor=None)InvoicePageitems (InvoiceView) and next_cursor. Newest first; limit is 1 to 100.

An InvoiceView has id, status, billing_reason, currency, amount_due, amount_paid, amount_remaining, period_start, period_end, created_at, hosted_invoice_url and invoice_pdf.

machine.consumption

MethodReturnsDescription
report(user_id, key, value, *, idempotency_key=None)ConsumptionResultReports value units of key. aggregate is the running total (key, total as a decimal string) and metered is True when the key prices a metered feature.
list_aggregates(user_id)list[ConsumptionAggregate]Every running total of a user: key, total and updated_at.
get_aggregate(user_id, key)ConsumptionAggregateOne running total. Raises API_001 with details["apiCode"] CONS_003 when the key was never reported.

report validates before sending and raises CFG_001 for an empty user_id, a key that is not 1 to 64 characters of a-zA-Z0-9., a non-finite or non-numeric value (a bool is refused), or an idempotency_key that is empty or longer than 200 characters once trimmed.

Copyright © 2026