OAuth2 Introspection Guard¶
oauth2_introspection(...) — validates opaque tokens via RFC 7662 token introspection.
Requires: pip install "lauren-guards[http]".
Signature¶
def oauth2_introspection(
*,
introspection_url: str,
client_id: str,
client_secret: str,
sub_claim: str = "sub",
role_claim: str | None = None,
scope_claim: str = "scope",
cache_seconds: int = 60,
issuer: str | None = None,
audience: str | Iterable[str] | None = None,
realm: str = "lauren",
timeout_seconds: float = 5.0,
) -> type:
...
Parameters:
| Parameter | Type | Default | Description |
|---|---|---|---|
introspection_url |
str |
— | Auth server's RFC 7662 introspection endpoint. |
client_id |
str |
— | Resource server client id (sent as Basic auth). |
client_secret |
str |
— | Resource server client secret. |
sub_claim |
str |
"sub" |
Response field used for AuthUser.id. |
role_claim |
str \| None |
None |
Response field for roles. |
scope_claim |
str |
"scope" |
Response field for scopes (space-separated or list). |
cache_seconds |
int |
60 |
Per-token cache TTL; 0 disables caching. |
issuer |
str \| None |
None |
Required iss in the response when set. |
audience |
str \| Iterable[str] \| None |
None |
Required aud in the response when set. |
realm |
str |
"lauren" |
Surfaced in error responses. |
timeout_seconds |
float |
5.0 |
HTTP timeout for the introspection call. |
Usage¶
import os
from lauren_guards import oauth2_introspection
OAuth2Guard = oauth2_introspection(
introspection_url="https://auth.example.com/introspect",
client_id=os.environ["OAUTH2_CLIENT_ID"],
client_secret=os.environ["OAUTH2_CLIENT_SECRET"],
)
The guard POSTs the bearer token to the introspection endpoint (form-encoded
token=), authenticating as the resource server with HTTP Basic. If the
response active field is not True, the guard rejects with 401. On
success it stamps AuthUser (credential_type="oauth2") on
request.state.user.
Failed introspection calls (5xx, malformed JSON, non-object responses)
are wrapped as UnauthorizedError. Successful introspection results are
cached per token for cache_seconds so repeated requests with the same
token don't hammer the auth server.
When to reach for this guard¶
Use oauth2_introspection when your tokens are opaque (no local JWT
verification possible) and you already run an OAuth2 authorization server
that exposes RFC 7662 introspection — e.g. Keycloak, Auth0, Okta, or a
custom provider.