Authentication¶
auth
¶
Authentication: who is calling, and whether they may.
from oxbrook import App, Depends, Request, Router
from oxbrook.auth import APIKey, JWT, Principal, optional, principal
tokens = JWT(key=SECRET, algorithms=["HS256"], audience="notes")
keys = APIKey(header="x-api-key", verify=lookup_key)
app = App(auth=tokens | keys) # every route, by default
@app.get("/health", auth=None) # public, on purpose
async def health(_: Request): ...
@app.post("/notes", auth=tokens.requires("notes:write"))
async def create(_: Request, note: NoteIn, who: Principal = Depends(principal)): ...
Three ideas. A scheme finds a credential in a request and checks it. A
principal is who it found. A requirement is what a route demands of
that principal. auth= on an app, a router, a route or a WebSocket declares
all three at once, and the nearest declaration wins.
The rules the framework enforces. Schemes are tried in the order written,
and the first one that finds a credential of its kind decides: a credential
that is present and wrong answers 401 and never falls through to the next
scheme or to anonymous access. Missing or wrong credentials are 401, with a
WWW-Authenticate challenge for each scheme that has one; a principal that
fails a requirement is 403. Authentication runs before the request body is
read and before any router middleware or handler, so a refused caller never
makes the server take in what they sent.
A scheme is any object with async authenticate(request) returning a
Principal, returning None when the request carries no credential of its kind,
and raising Unauthenticated when it carries one that is wrong. Subclass
Scheme to get | and .requires(...) as well.
Principal
dataclass
¶
Principal(
subject: str,
scheme: str = "",
scopes: frozenset[str] = frozenset(),
roles: frozenset[str] = frozenset(),
claims: Mapping[str, Any] = dict(),
user: Any = None,
)
Who a scheme found: the same shape whatever the credential was.
subject identifies the caller — a user id, a key id, a client id — and
is a string, so str(user.id) rather than the id itself. scheme is the
name of the scheme that found it, filled in by the framework when left
empty. scopes are what the credential grants the client, and roles
what the caller is, as an identity provider assigns them; requires(...)
checks both. claims is anything else the credential carried, and user
whatever a verify function looked up, if anything.
Scopes and roles are kept apart because providers issue them separately, and a role that shares a name with a scope must not grant it.
Scheme
¶
Bases: _Combinable
A way of finding and checking a credential.
Subclass it and write authenticate:
class Signature(Scheme):
name = "signature"
async def authenticate(self, request):
signature = request.header("x-signature")
if signature is None:
return None # not mine: try the next scheme
if not valid(signature, await request.read()):
raise Unauthenticated("bad signature") # mine, and wrong
return Principal(subject="webhook")
challenge gives the WWW-Authenticate header sent with a refusal, and
openapi the entry in the OpenAPI document's securitySchemes; both are
optional.
APIKey
¶
APIKey(
*,
header: str | None = None,
cookie: str | None = None,
verify: Callable[[str], Any],
name: str = "api_key",
)
Bases: Scheme
A key in a header or a cookie, looked up by its hash.
async def lookup_key(digest): # -> Principal, or None if unknown
row = await db.fetchrow("select * from api_keys where digest = $1", digest)
return None if row is None else Principal(
subject=row["id"], scopes=row["scopes"]
)
keys = APIKey(header="x-api-key", verify=lookup_key)
verify receives the key's SHA-256 digest, never the key, so what is
stored is the digest: a leaked table is not a list of working keys, and a
lookup by digest cannot be timed to recover a key byte by byte. Store
APIKey.digest(key) when issuing one; APIKey.generate() makes a key long
enough that an unsalted hash is the right tool.
Not the query string, which ends up in logs.
Source code in python/oxbrook/auth.py
digest
staticmethod
¶
generate
staticmethod
¶
authenticate
async
¶
authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
Bearer
¶
Bearer(
verify: Callable[[str], Any] | None = None,
*,
realm: str | None = None,
name: str = "bearer",
bearer_format: str | None = None,
)
Bases: Scheme
A token in Authorization: Bearer <token>, checked by verify.
async def check_token(token): # -> Principal, or None if invalid
record = await tokens.lookup(token)
return None if record is None else Principal(subject=record.user_id)
bearer = Bearer(verify=check_token)
For tokens this app can check itself, JWT does the verifying. verify is
for everything else: a provider SDK, an opaque token looked up in a
database or introspected at the issuer.
Refusals carry an RFC 6750 challenge: invalid_token for a token that did
not verify, insufficient_scope with the scopes needed for a 403.
Source code in python/oxbrook/auth.py
challenge
¶
challenge(error: HTTPError | None) -> str
Source code in python/oxbrook/auth.py
JWT
¶
JWT(
key: Any,
*,
algorithms: Iterable[str],
audience: str | Iterable[str] | None,
issuer: str | None = None,
leeway: float = 60,
scopes_claim: str | tuple[str, ...] = "scope",
roles_claim: str | tuple[str, ...] | None = None,
subject_claim: str = "sub",
claims: Mapping[str, Any] | None = None,
cache_size: int = _CACHE_SIZE,
realm: str | None = None,
name: str = "jwt",
)
Bases: _Signed
A JSON Web Token this app can verify itself.
tokens = JWT(key=os.environ["JWT_SECRET"], algorithms=["HS256"], audience="notes")
tokens = JWT(key=public_key_pem, algorithms=["RS256"], audience="notes",
issuer="https://login.example.com/")
Checked every time: the signature, exp with leeway seconds of clock
skew, nbf, aud against audience, and iss against issuer when one
is given. The principal's subject is the sub claim and its scopes the
scope claim, a space-separated string or a list; scopes_claim names a
different claim, such as "scp" or "permissions", and roles_claim
one to read roles from. Either may be a tuple naming a nested claim:
roles_claim=("realm_access", "roles"). claims= names claims that must
have a given value, or one of a list: claims={"token_use": "access"}.
algorithms is required, and cannot mix families: an HMAC secret with
HS*, or a public key with the asymmetric ones. Accepting both is how a
public key ends up used as an HMAC secret to forge a token, and none is
never accepted. An HMAC secret must be at least as long as the hash.
audience=None accepts a token for any audience, and has to be written
out: a token issued for another service is otherwise accepted by this one.
A token that verified is remembered until it expires, up to cache_size
of them, so a caller's next request skips the signature check; 0 turns
that off.
Needs PyJWT: pip install 'oxbrook[auth]'.
Source code in python/oxbrook/auth.py
OIDC
¶
OIDC(
issuer: str,
*,
audience: str | Iterable[str] | None,
algorithms: Iterable[str] | None = None,
scopes_claim: str | tuple[str, ...] = "scope",
roles_claim: str | tuple[str, ...] | None = None,
subject_claim: str = "sub",
claims: Mapping[str, Any] | None = None,
leeway: float = 60,
discovery_url: str | None = None,
keys_max_age: float = 300,
allow_http: bool = False,
timeout: float = 10,
cache_size: int = _CACHE_SIZE,
realm: str | None = None,
name: str = "oidc",
)
Bases: _Signed
Tokens from an OpenID Connect provider, checked against its published keys.
users = OIDC("https://login.example.com/realms/acme", audience="notes-api")
users = OIDC.auth0("acme.eu.auth0.com", audience="https://notes.example.com")
The provider's discovery document, /.well-known/openid-configuration
under the issuer, says where its signing keys are. They are fetched on
the first token, once for the whole process however many worker loops
ask, and again every keys_max_age seconds so that a key the provider
withdraws stops being accepted. A token signed with a key id not yet seen
fetches them again at once — how a provider's key rotation arrives — but
at most once a minute, so tokens with made-up key ids cannot turn into a
stream of requests to the provider. Call await scheme.load() from a
lifespan to fetch them at startup instead, and fail there if the provider
is unreachable.
Only public-key algorithms are accepted, those the provider advertises,
and each only with a key of its own type: never none, never HMAC, so a
provider's public key cannot be used as a shared secret to forge a token.
algorithms= narrows the list further. Every token is checked for its
signature, iss, aud, exp and nbf, with leeway seconds of clock
skew; claims are read as in JWT, including roles_claim and claims=.
When the provider cannot be reached before any keys were fetched, the
answer is 503 rather than 401: the token may well be good, and a 401
tells a client to throw it away.
The issuer must be HTTPS, since keys fetched over plain HTTP can be
replaced in transit; http://localhost is allowed for development, and
allow_http=True for a provider on a private network.
The class methods set up known providers: keycloak, auth0, entra,
okta, cognito, google and firebase. Each takes the same keyword
arguments as OIDC itself, to override what it sets.
Source code in python/oxbrook/auth.py
keys
instance-attribute
¶
keys = _jwks.KeySet(
discovery_url,
issuer,
algorithms=algorithms,
allow_http=allow_http,
timeout=timeout,
max_age=keys_max_age,
changed=self._verified.clear,
)
load
async
¶
Fetch the discovery document and keys now, raising if that fails.
Source code in python/oxbrook/auth.py
openapi
¶
keycloak
classmethod
¶
keycloak(
url: str, realm: str, *, audience: Any, **options: Any
) -> OIDC
Keycloak: OIDC.keycloak("https://sso.example.com", "acme", audience="notes-api").
Scopes from scope, roles from the realm roles in realm_access. For
a client's own roles, roles_claim=("resource_access", client, "roles").
Keycloak puts a client in aud only through an audience mapper, which
the API's clients need.
Source code in python/oxbrook/auth.py
auth0
classmethod
¶
auth0(
domain: str, *, audience: Any, **options: Any
) -> OIDC
Auth0: OIDC.auth0("acme.eu.auth0.com", audience="https://notes.example.com").
audience is the API's identifier. Scopes from scope; with RBAC's
"Add Permissions in the Access Token", scopes_claim="permissions".
Source code in python/oxbrook/auth.py
entra
classmethod
¶
entra(
tenant_id: str,
*,
audience: Any,
version: int = 2,
**options: Any,
) -> OIDC
Microsoft Entra ID: OIDC.entra(tenant_id, audience=api_client_id).
tenant_id is the directory's GUID; common and organizations
name no single issuer and are refused. Scopes from scp, app roles
from roles. An API's access tokens are version 1 unless its manifest
sets requestedAccessTokenVersion to 2, and the two have different
issuers: pass version=1 for those.
Source code in python/oxbrook/auth.py
okta
classmethod
¶
okta(
domain: str,
*,
audience: Any,
server: str = "default",
**options: Any,
) -> OIDC
Okta: OIDC.okta("acme.okta.com", audience="api://default").
A custom authorization server, default unless server names
another; the org server's access tokens are for Okta alone to verify.
Scopes from scp.
Source code in python/oxbrook/auth.py
cognito
classmethod
¶
cognito(
region: str,
user_pool_id: str,
*,
client_id: str | Iterable[str],
**options: Any,
) -> OIDC
Amazon Cognito: OIDC.cognito("eu-west-1", "eu-west-1_AbC123", client_id="...").
Cognito access tokens carry no aud: the app client is in
client_id, which is checked instead, along with token_use being
access so an ID token is not accepted in its place. Scopes from
scope, groups as roles from cognito:groups.
Source code in python/oxbrook/auth.py
google
classmethod
¶
google(
client_id: str | Iterable[str], **options: Any
) -> OIDC
Google ID tokens, from Sign in with Google: OIDC.google(client_id).
Identity only: Google's tokens carry no scopes for an API. aud is
the app's OAuth client id, and iss either of the two forms Google
uses.
Source code in python/oxbrook/auth.py
firebase
classmethod
¶
firebase(project_id: str, **options: Any) -> OIDC
Firebase Authentication ID tokens: OIDC.firebase("acme-app").
aud is the project id. Custom claims set through the Admin SDK are
top-level claims, so roles_claim="roles" reads a roles list.
Source code in python/oxbrook/auth.py
Basic
¶
Basic(
verify: Callable[[str, str], Any],
*,
realm: str = "api",
name: str = "basic",
allow_http: bool = False,
)
Bases: Scheme
A username and password in Authorization: Basic ....
async def check_password(username, password): # -> Principal, or None
user = await users.find(username)
if user is None or not hasher.verify(user.password_hash, password):
return None
return Principal(subject=str(user.id), user=user)
staff = Basic(verify=check_password)
Refused over plain HTTP, since the password crosses the network readable.
HTTPS, a proxy that sets X-Forwarded-Proto: https, and loopback are all
accepted; allow_http=True accepts anything.
Compare the password against a slow hash — argon2, bcrypt, scrypt — in
verify: a password is not a random key, and a fast hash of one is
cracked offline.
Source code in python/oxbrook/auth.py
authenticate
async
¶
authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
SessionAuth
¶
SessionAuth(
sessions: Any,
*,
key: str = "user_id",
load: Callable[[Any], Any] | None = None,
name: str = "session",
csrf: bool = True,
trusted_origins: Iterable[str] | None = None,
)
Bases: Scheme
The user a signed session cookie says is logged in.
sessions = Sessions(secret=SECRET)
@app.post("/login", auth=None)
async def login(_: Request, form: Login = Form(), session=Depends(sessions.load)):
user = await check(form)
session["user_id"] = user.id
web = SessionAuth(sessions, key="user_id", load=load_user)
load turns the stored value into the user, and may return a Principal
to set scopes. With no load, the value itself is the subject.
A session cookie that does not verify, has expired, or names a user
load cannot find counts as no session rather than a wrong credential. A
browser sends the cookie on its own, and the person using it cannot remove
a stale one; refusing it outright would lock them out of pages that accept
anonymous visitors, until the cookie expired.
Cross-site requests are refused. A browser sends the session cookie with a request another site's page makes, so a request that changes state — anything but GET, HEAD and OPTIONS — must show it came from this site:
Sec-Fetch-Site: same-originornone, which browsers set themselves;- otherwise an
Originnaming this server, or one oftrusted_origins; - with neither header, an
X-CSRF-Tokenheader equal to the session's token, fromcsrf_token(session).
Anything else is 403. trusted_origins defaults to the app's CORS
origins: a page allowed to call the API with credentials is trusted to.
csrf=False turns the check off, for an app that does its own.
Source code in python/oxbrook/auth.py
csrf_token
staticmethod
¶
The session's CSRF token, made on first use.
For a request that carries neither Sec-Fetch-Site nor Origin —
an old browser, mostly — to send as X-CSRF-Token. Render it into the
page, or return it from an endpoint the page's script reads.
Source code in python/oxbrook/auth.py
authenticate
async
¶
authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
Tickets
¶
Bases: Scheme
Short-lived tickets for opening a WebSocket from a browser.
tickets = Tickets()
@app.post("/ws-ticket", auth=users)
async def ws_ticket(_: Request, who: Principal = Depends(principal)):
return {"ticket": tickets.issue(who)}
@app.websocket("/feed", auth=tickets)
async def feed(_: Request, ws, who: Principal = Depends(principal)): ...
A browser cannot set Authorization on a WebSocket, and a token in the
URL ends up in proxy logs and history. A ticket goes in the URL instead —
new WebSocket("wss://.../feed?ticket=...") — and is safe there because
it is good for one connection, within ttl seconds (30 by default), and
for nothing else. The socket's principal is the one it was issued for.
Only a WebSocket upgrade reads one: on any other request a ticket in the query string is ignored, and no other scheme reads the query string.
Tickets are kept in the process that issued them. Behind a load balancer with several processes, the socket must reach the process the ticket came from.
Source code in python/oxbrook/auth.py
issue
¶
issue(who: Principal) -> str
A new ticket for who, good for one socket within ttl seconds.
Source code in python/oxbrook/auth.py
authenticate
async
¶
authenticate(request: Any) -> Principal | None
Source code in python/oxbrook/auth.py
OAuthLogin
¶
OAuthLogin(
issuer: str,
*,
client_id: str,
client_secret: str | None,
sessions: Any,
scopes: Iterable[str] = ("openid", "email", "profile"),
on_login: Callable[[Any, Login], Any] | None = None,
key: str = "user_id",
redirect_uri: str | None = None,
after_login: str = "/",
after_logout: str = "/",
params: Mapping[str, str] | None = None,
trusted_origins: Iterable[str] | None = None,
discovery_url: str | None = None,
allow_http: bool = False,
timeout: float = 10,
name: str = "oidc",
)
Logging people in through an identity provider.
sessions = Sessions(secret=os.environ["SECRET_KEY"])
google = OAuthLogin.google(
client_id=os.environ["GOOGLE_CLIENT_ID"],
client_secret=os.environ["GOOGLE_CLIENT_SECRET"],
sessions=sessions,
on_login=find_or_create_user,
)
app.include(google.routes(prefix="/auth")) # /auth/login, /auth/callback, /auth/logout
web = SessionAuth(sessions, key="user_id", load=load_user)
A link to /auth/login?next=/notes sends the person to the provider;
the provider sends them back to /auth/callback, which finishes the login
and redirects to /notes. next is followed only when it is a path on
this site. POST /auth/logout empties the session.
on_login(request, login) is where the app decides who that is: it
receives a Login, and returns the value to keep in the session under
key — usually the app's own user id, after finding or creating the user.
Returning None refuses the login with 403. It may be async, and
receives the request so it can reach a pool from request.state. With no
on_login the value kept is "<name>:<subject>", such as
"google:1161...".
What the flow checks. state must match a login this browser started,
within ten minutes, and is good once. PKCE (S256) binds the code to that
login too, so a code intercepted on its way back is useless elsewhere. For
OpenID Connect providers the ID token is checked like any OIDC token —
signature, issuer, audience (the client id), expiry — and its nonce must
be this login's. An iss parameter on the callback must name the
provider, which stops a callback from one provider being passed to
another's endpoint. The session is emptied before the new value goes in,
so nothing written into it before the login survives it.
The redirect URI must be registered with the provider exactly. It is
worked out from the request unless redirect_uri= gives it; give it
behind a proxy that changes the host or the scheme.
The session cookie must be SameSite=Lax or None: the callback arrives
as a navigation from the provider's site, which a Strict cookie is not
sent with.
OAuthLogin(issuer, ...) works with any OpenID Connect provider that
serves discovery. The class methods set up google, microsoft,
github and keycloak.
Source code in python/oxbrook/_login.py
load
async
¶
Fetch the provider's discovery document and keys now, raising if that fails: from a lifespan, to find an unreachable provider at startup.
google
classmethod
¶
google(
*,
client_id: str,
client_secret: str,
sessions: Any,
**options: Any,
) -> OAuthLogin
Sign in with Google.
The OAuth client comes from the Google Cloud console, as a "Web
application" with the callback URL as an authorized redirect URI.
claims["hd"] is the Workspace domain, for an app that admits one
organisation's accounts only. params={"access_type": "offline"}
asks for a refresh token.
Source code in python/oxbrook/_login.py
microsoft
classmethod
¶
microsoft(
*,
client_id: str,
client_secret: str,
sessions: Any,
tenant: str = "common",
authority: str = "https://login.microsoftonline.com",
**options: Any,
) -> OAuthLogin
Sign in with Microsoft: work and school accounts, personal ones, or both.
tenant says whose accounts may log in: common (the default) any
Microsoft account, organizations any work or school account,
consumers personal accounts only, or a directory's tenant id for
that organisation alone. For the first two the ID token's issuer
names the person's own tenant, and is checked against its tid
claim. authority is for a national cloud.
Microsoft does not verify the email claim, so email_verified is
False: key accounts on subject, and claims["tid"] with it for a
multi-tenant app.
Source code in python/oxbrook/_login.py
keycloak
classmethod
¶
keycloak(
url: str,
realm: str,
*,
client_id: str,
client_secret: str | None,
sessions: Any,
**options: Any,
) -> OAuthLogin
A Keycloak realm: OAuthLogin.keycloak("https://sso.example.com", "acme", ...).
The client needs the standard flow enabled, the callback URL among its
valid redirect URIs, and PKCE's S256 method allowed.
Source code in python/oxbrook/_login.py
github
classmethod
¶
github(
*,
client_id: str,
client_secret: str,
sessions: Any,
server: str = "https://github.com",
api: str = "https://api.github.com",
**options: Any,
) -> OAuthLogin
Sign in with GitHub, through an OAuth app.
GitHub is OAuth 2 without OpenID Connect: there is no ID token, so
who logged in is read from its API with the access token instead.
subject is the account's numeric id as a string — the login name
can be changed and then taken by someone else. The email is the
primary verified address when the user:email scope is granted.
For GitHub Enterprise Server, server="https://github.example.com"
and api="https://github.example.com/api/v3".
Source code in python/oxbrook/_login.py
routes
¶
routes(
prefix: str = "",
*,
login: str = "/login",
callback: str = "/callback",
logout: str = "/logout",
) -> Any
A router with the three routes, all public: include it in the app.
GET login starts a login, GET callback is where the provider sends
the person back, and POST logout ends the session. Two providers
need two prefixes, such as /auth/google and /auth/github.
Source code in python/oxbrook/_login.py
Login
dataclass
¶
Login(
provider: str,
subject: str,
email: str | None = None,
email_verified: bool = False,
name: str | None = None,
claims: Mapping[str, Any] = dict(),
tokens: Mapping[str, Any] = dict(),
)
Who the provider says logged in, as on_login receives it.
subject is the provider's stable id for the person: key accounts on
(provider, subject), never on the email address, which a person can
change and some providers do not verify. email_verified is True only
when the provider said so. claims is the verified ID token's claims, or
for GitHub the user as its API describes them. tokens is the provider's
token response — the access token, and a refresh token if one was asked
for — for an app that calls the provider's API later; it is not kept
anywhere unless the app keeps it, and it is left out of repr.
tokens
class-attribute
instance-attribute
¶
LoginFailed
¶
Bases: HTTPError
A login that could not be completed.
400 for a callback that does not belong to a login this browser started
(or one already finished, or too old), 403 when the provider or the
app's on_login refused the person, 502 or 503 when the provider
could not be reached or answered nonsense. detail is written for the
person; why, exactly, goes to the oxbrook.auth log. Register an
exception handler for it to show a page rather than problem details.
Source code in python/oxbrook/_login.py
Unauthenticated
¶
Bases: HTTPError
401: the request carries no acceptable credential.
Raised by a scheme for a credential that is present and wrong, which stops
the search: the next scheme is not tried. detail reaches the client, so
say what kind of wrong it is — expired, invalid — and log the rest.
Source code in python/oxbrook/auth.py
Forbidden
¶
Forbidden(
detail: str | None = None,
headers: dict[str, Any] | None = None,
*,
scopes: Iterable[str] = (),
roles: Iterable[str] = (),
**kwargs: Any,
)
Bases: HTTPError
403: the caller is known, and may not do this.
Raised by the framework when a principal fails a requirement, and the way
a handler refuses a rule about a particular record: raise Forbidden()
when the note belongs to someone else. Retrying with the same credential
will not help, which is what separates it from 401.
Source code in python/oxbrook/auth.py
Requirement
dataclass
¶
Requirement(
all_of: frozenset[str] = frozenset(),
any_of: frozenset[str] = frozenset(),
check: Callable[..., Any] | None = None,
roles: frozenset[str] = frozenset(),
)
What .requires(...) asks of a principal.
met
async
¶
met(found: Principal, request: Any) -> bool
Source code in python/oxbrook/auth.py
principal
¶
principal(request: Any) -> Principal | None
Who authentication found for this request, or None.
A dependency, who: Principal = Depends(principal), and a plain function
for middleware. None on a route with no auth=, and for an anonymous
caller on one declared optional(...).
Source code in python/oxbrook/auth.py
optional
¶
Accept anonymous callers too.
@app.get("/feed", auth=optional(tokens))
async def feed(_: Request, who=Depends(principal)): ... # None if anonymous
Only a request with no credential is anonymous. One carrying a wrong credential is still refused: an expired token is not the same as none, and treating it so would hide from the client that it needs a new one.