Skip to content

OIDC

Requires the oidc extra:

uv add "rn-forge-auth[oidc]"

rn_forge.auth.oidc is not re-exported from rn_forge.auth — import it directly:

from rn_forge.auth.oidc import OidcAuthenticator

rn_forge.auth.oidc

OIDC: discovery, the login provider, one validation profile per kind of token (access, ID and logout) and the authenticator that maps verified access-token claims to a :class:~rn_forge.auth.Principal.

:class:OidcProvider runs the authorization code flow with PKCE over Authlib's OAuth2Session and verifies the ID token with :class:IdTokenVerifier.

A token is accepted only by the profile used at its own place: the claims and the typ header each profile requires exclude the others.

:class:TokenVerificationError carries the specific failure reason. Log it; never send it to the client.

Requires the oidc extra. Not imported by :mod:rn_forge.auth; import this module directly.

ClaimMapper = Callable[[str, Mapping[str, Any]], ExternalIdentity]

Maps (provider ID, verified claims) to an identity.

The claims are the ID token's, completed by UserInfo for any claim the ID token lacks. Raise :class:~rn_forge.auth.LoginFailed to refuse the login.

FetchJson = Callable[[str], Mapping[str, Any]]

A transport: GET a URL and return the decoded JSON object.

TokenHook = Callable[[ExternalIdentity, UpstreamTokens], None]

Receives the identity and the upstream tokens of a successful login.

TokenMode = Literal['rfc9068', 'rfc7519']

The access-token standard a provider issues: RFC 9068 JWT access tokens, or plain RFC 7519 JWTs.

BackchannelLogout(verifier, accounts)

Validates a back-channel logout token and says what it revokes.

The handler changes no state besides the verifier's jti record: the binding applies the returned :class:LogoutRevocation, because the revoked-sid lifetime (the sessions' absolute timeout) and the session-version store belong to it.

Parameters:

Name Type Description Default
verifier LogoutTokenVerifier

The logout-token profile for this provider.

required
accounts AccountResolver

Finds the account behind (issuer, sub); never provisions.

required

handle(logout_token)

Verify logout_token and return what to revoke.

A token with a sid revokes that session only, even if it also has a sub.

Raises:

Type Description
TokenVerificationError

The token fails the logout-token profile, including a replayed jti. The message is for logs; answer 400.

IdTokenVerifier(*, jwks, issuer, client_id, algorithms=('RS256',), leeway=0.0, max_age=None)

The ID-token profile: verify an ID token at the OIDC callback.

Authlib's CodeIDToken checks iss, aud, azp, exp, iat, nonce and at_hash. Added here: the algorithm allow-list, a mandatory non-empty nonce, auth_time within max_age, and a typ header that is absent or JWT (case-insensitive).

Parameters:

Name Type Description Default
jwks PyJWKClient

Where signing keys come from.

required
issuer str

The exact iss accepted.

required
client_id str

The OIDC login client ID; the aud and azp expected.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age int | None

When set, the most seconds that may separate the token's auth_time from now; auth_time is then required.

None

from_issuer(issuer, *, client_id, fetch=fetch_json, algorithms=('RS256',), leeway=0.0, max_age=None, lifespan=300.0, cooldown_duration=30.0) classmethod

Build a verifier by OIDC discovery on issuer.

Parameters:

Name Type Description Default
issuer str

The IdP's issuer URL.

required
client_id str

The OIDC login client ID.

required
fetch FetchJson

The transport for the discovery document.

fetch_json
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age int | None

See the class docstring.

None
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0

Raises:

Type Description
TokenVerificationError

Discovery failed, returned no jwks_uri, or the jwks_uri is not HTTPS (or HTTP to a local host).

from_jwks_url(jwks_url, *, issuer, client_id, algorithms=('RS256',), leeway=0.0, max_age=None, lifespan=300.0, cooldown_duration=30.0) classmethod

Build a verifier from a known JWKS URL, skipping discovery.

Parameters:

Name Type Description Default
jwks_url str

Where the key set is served.

required
issuer str

The exact iss accepted.

required
client_id str

The OIDC login client ID.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age int | None

See the class docstring.

None
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0

Raises:

Type Description
TokenVerificationError

jwks_url is not HTTPS (or HTTP to a local host).

verify(token, *, nonce, access_token=None)

Return token's claims once it satisfies the ID-token profile.

Parameters:

Name Type Description Default
token str

The ID token.

required
nonce str

The nonce sent in the authorization request. Must be non-empty.

required
access_token str | None

The access token returned with the ID token. When given and the ID token has at_hash, the hash must match.

None

Raises:

Type Description
TokenVerificationError

For any failure; the message says which.

JwtVerifier(*, jwks, issuer, audience, algorithms=('RS256',), leeway=0.0, mode='rfc7519', login_client_id=None)

The access-token profile: verify a bearer JWT against a key set, an issuer and an audience.

mode="rfc9068" accepts only RFC 9068 access tokens: a typ header of at+jwt or application/at+jwt (case-insensitive), and iss, exp, aud, sub, client_id, iat and jti present. mode="rfc7519" accepts a typ of JWT (case-insensitive) or none, requires iss, aud and exp, and validates sub, nbf and iat when present.

In both modes a token carrying nonce or events (an ID token or a logout token) is rejected, iss must equal the configured issuer, and aud must contain one of the configured audiences. The algorithm allow-list is what rejects alg: none and an HMAC token signed with the public key.

Parameters:

Name Type Description Default
jwks PyJWKClient

Where signing keys come from. It caches the key set and refetches for an unknown kid at most once per its cooldown_duration.

required
issuer str

The exact iss accepted.

required
audience str | Sequence[str]

The aud accepted — one value, or any of several.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated on exp/nbf/iat.

0.0
mode TokenMode

The access-token standard the provider issues.

'rfc7519'
login_client_id str | None

The OIDC login client ID of this application, if any.

None

Raises:

Type Description
ValueError

login_client_id is one of the accepted audiences and mode is not "rfc9068".

from_issuer(issuer, *, audience, fetch=fetch_json, algorithms=('RS256',), leeway=0.0, lifespan=300.0, cooldown_duration=30.0, mode='rfc7519', login_client_id=None) classmethod

Build a verifier by OIDC discovery on issuer.

Discovery runs once, here. Build the verifier at startup, not per request.

Parameters:

Name Type Description Default
issuer str

The IdP's issuer URL.

required
audience str | Sequence[str]

The aud accepted — one value, or any of several.

required
fetch FetchJson

The transport for the discovery document. The key set is fetched by :class:jwt.PyJWKClient.

fetch_json
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches. An unknown kid triggers a refetch only after this long.

30.0
mode TokenMode

The access-token standard the provider issues.

'rfc7519'
login_client_id str | None

The OIDC login client ID of this application.

None

Raises:

Type Description
TokenVerificationError

Discovery failed, returned no jwks_uri, or the jwks_uri is not HTTPS (or HTTP to a local host).

ValueError

See the class docstring.

from_jwks_url(jwks_url, *, issuer, audience, algorithms=('RS256',), leeway=0.0, lifespan=300.0, cooldown_duration=30.0, mode='rfc7519', login_client_id=None) classmethod

Build a verifier from a known JWKS URL, skipping discovery.

Parameters:

Name Type Description Default
jwks_url str

Where the key set is served.

required
issuer str

The exact iss accepted.

required
audience str | Sequence[str]

The aud accepted — one value, or any of several.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches. An unknown kid triggers a refetch only after this long.

30.0
mode TokenMode

The access-token standard the provider issues.

'rfc7519'
login_client_id str | None

The OIDC login client ID of this application.

None

Raises:

Type Description
TokenVerificationError

jwks_url is not HTTPS (or HTTP to a local host).

ValueError

See the class docstring.

verify(token)

Return token's claims once it satisfies the access-token profile.

Raises:

Type Description
TokenVerificationError

For any failure; the message says which.

LogoutRevocation(issuer, sid=None, subject=None, account_id=None) dataclass

What a valid back-channel logout token asks to revoke.

With a sid, revoke that one session: ReplayStore.revoke_sid(issuer, sid, ...). Without one, bump the session version of account_id, or do nothing when it is None.

Attributes:

Name Type Description
issuer str

The token's iss.

sid str | None

The session ID to revoke, if the token names one.

subject str | None

The token's sub, if present.

account_id str | None

For a token without sid, the account linked to (issuer, subject); None when none is linked.

LogoutTokenVerifier(*, jwks, issuer, client_id, replay_store, algorithms=('RS256',), leeway=0.0, max_age_seconds=120.0)

The logout-token profile: verify an OIDC Back-Channel Logout token.

Back-Channel Logout 1.0 §2.6 requires iss, aud, iat, exp, jti and events; events must be an object whose http://schemas.openid.net/event/backchannel-logout member is an object; sid or sub must be present; nonce must be absent. Added here: the typ header is logout+jwt (optionally prefixed application/, case-insensitive) or absent; iat is at most max_age_seconds old; and a jti is accepted once. The jti is recorded in replay_store under "{iss}|{jti}" until the token's exp (at least one second), after every other check has passed.

Parameters:

Name Type Description Default
jwks PyJWKClient

Where signing keys come from.

required
issuer str

The exact iss accepted.

required
client_id str

The OIDC login client ID; the aud expected.

required
replay_store ReplayStore

Remembers the jti values already accepted.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age_seconds float

The oldest iat, in seconds, accepted.

120.0

from_issuer(issuer, *, client_id, replay_store, fetch=fetch_json, algorithms=('RS256',), leeway=0.0, max_age_seconds=120.0, lifespan=300.0, cooldown_duration=30.0) classmethod

Build a verifier by OIDC discovery on issuer.

Parameters:

Name Type Description Default
issuer str

The IdP's issuer URL.

required
client_id str

The OIDC login client ID.

required
replay_store ReplayStore

Remembers the jti values already accepted.

required
fetch FetchJson

The transport for the discovery document.

fetch_json
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age_seconds float

The oldest iat, in seconds, accepted.

120.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0

Raises:

Type Description
TokenVerificationError

Discovery failed, returned no jwks_uri, or the jwks_uri is not HTTPS (or HTTP to a local host).

from_jwks_url(jwks_url, *, issuer, client_id, replay_store, algorithms=('RS256',), leeway=0.0, max_age_seconds=120.0, lifespan=300.0, cooldown_duration=30.0) classmethod

Build a verifier from a known JWKS URL, skipping discovery.

Parameters:

Name Type Description Default
jwks_url str

Where the key set is served.

required
issuer str

The exact iss accepted.

required
client_id str

The OIDC login client ID.

required
replay_store ReplayStore

Remembers the jti values already accepted.

required
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
max_age_seconds float

The oldest iat, in seconds, accepted.

120.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0

Raises:

Type Description
TokenVerificationError

jwks_url is not HTTPS (or HTTP to a local host).

verify(token)

Return token's claims once it satisfies the logout-token profile.

Raises:

Type Description
TokenVerificationError

For any failure, including a jti already accepted; the message says which.

OAuth2Endpoints(authorization, token, user) dataclass

The endpoints of an OAuth 2.0 provider that has no discovery document.

Attributes:

Name Type Description
authorization str

The authorization endpoint.

token str

The token endpoint.

user str

The endpoint that returns the signed-in user as a JSON object.

OidcAuthenticator(verifier, *, claims_to_principal=principal_from_claims)

An :class:~rn_forge.auth.Authenticator backed by a :class:JwtVerifier.

The verifier holds the JWKS cache; build one authenticator and reuse it.

The reason a token was rejected is carried on the raised :class:~rn_forge.web.exceptions.AuthenticationFailed, for logging. It is not part of the 401 response body, which is :data:~rn_forge.web.AUTH_FAILED_DETAIL.

Parameters:

Name Type Description Default
verifier JwtVerifier

Verifies the bearer token and returns its claims.

required
claims_to_principal ClaimsToPrincipal

Verified claims → principal. Defaults to :func:~rn_forge.auth.principal_from_claims.

principal_from_claims

authenticate(*, credentials)

See :meth:rn_forge.auth.Authenticator.authenticate.

Raises:

Type Description
AuthenticationFailed

The token failed verification, or credentials carry a scheme other than Bearer.

from_issuer(issuer, *, audience, claims_to_principal=principal_from_claims, fetch=fetch_json, algorithms=('RS256',), leeway=0.0, lifespan=300.0, cooldown_duration=30.0, mode='rfc7519', login_client_id=None) classmethod

Build an authenticator by OIDC discovery on issuer.

Discovery runs once, here.

Parameters:

Name Type Description Default
issuer str

The IdP's issuer URL. Its /.well-known/openid-configuration supplies the jwks_uri.

required
audience str | Sequence[str]

The aud accepted — one value, or any of several.

required
claims_to_principal ClaimsToPrincipal

See the class docstring.

principal_from_claims
fetch FetchJson

The JSON transport for the discovery document.

fetch_json
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0
mode TokenMode

See :class:JwtVerifier.

'rfc7519'
login_client_id str | None

See :class:JwtVerifier.

None

Raises:

Type Description
TokenVerificationError

Discovery failed, returned no jwks_uri, or the jwks_uri is not HTTPS (or HTTP to a local host).

ValueError

See :class:JwtVerifier.

from_jwks_url(jwks_url, *, issuer, audience, claims_to_principal=principal_from_claims, algorithms=('RS256',), leeway=0.0, lifespan=300.0, cooldown_duration=30.0, mode='rfc7519', login_client_id=None) classmethod

Build an authenticator from a known JWKS URL, skipping discovery.

Parameters:

Name Type Description Default
jwks_url str

Where the key set is served.

required
issuer str

The exact iss accepted.

required
audience str | Sequence[str]

The aud accepted — one value, or any of several.

required
claims_to_principal ClaimsToPrincipal

See the class docstring.

principal_from_claims
algorithms Sequence[str]

The signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
lifespan float

Seconds a fetched key set stays cached.

300.0
cooldown_duration float

The fewest seconds between two key set fetches.

30.0
mode TokenMode

See :class:JwtVerifier.

'rfc7519'
login_client_id str | None

See :class:JwtVerifier.

None

Raises:

Type Description
TokenVerificationError

jwks_url is not HTTPS (or HTTP to a local host).

ValueError

See :class:JwtVerifier.

OidcConfiguration(issuer, jwks_uri, metadata=dict[str, Any]()) dataclass

The two members of an OIDC discovery document verification needs.

Attributes:

Name Type Description
issuer str

The document's issuer.

jwks_uri str

Where the key set is served.

metadata Mapping[str, Any]

The whole discovery document.

OidcProvider(*, id, issuer, client_id, client_secret, redirect_uri, scopes=None, max_age=None, userinfo='auto', claim_mapper=default_claim_mapper, token_hook=None, fetch=fetch_json, algorithms=('RS256',), leeway=0.0, timeout=5.0, token_endpoint_auth_method='client_secret_basic', rp_initiated_logout=False, endpoints=None, subject_field='sub', response_issuer=None)

Bases: IdentityProvider[LoginRequest]

An OIDC :class:~rn_forge.auth.IdentityProvider: authorization code flow with PKCE (S256), over Authlib's OAuth2Session.

The authorization request carries state, a nonce, the PKCE challenge and max_age when set; all of them are recorded on the login transaction. The callback is accepted only when its state equals the transaction's, its iss (RFC 9207) names the issuer, the code exchange succeeds and the ID token satisfies :class:IdTokenVerifier. The upstream tokens are discarded unless token_hook is given.

:meth:oauth2 builds the provider for a server with no ID token: kind is "oauth2", the request carries no nonce, and the identity comes from the user endpoint called with the access token.

Parameters:

Name Type Description Default
id str

The provider ID.

required
issuer str

The IdP's issuer URL; its discovery document is read on first use. For an OAuth 2.0 provider, the fixed issuer of its identities.

required
client_id str

The registered client.

required
client_secret str | None

The client's secret; None for a public client.

required
redirect_uri str

The registered callback URL.

required
scopes Sequence[str] | None

The requested scopes; OIDC requires openid. Defaults to openid email profile, or to none for an OAuth 2.0 provider.

None
max_age int | None

When set, the most seconds since the user authenticated; sent on the authorization request and enforced on the ID token.

None
userinfo UserInfoMode

"always" calls the UserInfo endpoint, "never" does not, and "auto" calls it when the ID token has no email. The UserInfo sub must equal the ID token's.

'auto'
claim_mapper ClaimMapper

Replaces :func:default_claim_mapper.

default_claim_mapper
token_hook TokenHook | None

Called with the identity and the upstream tokens after a successful login.

None
fetch FetchJson

The transport for the discovery document.

fetch_json
algorithms Sequence[str]

The ID-token signature algorithms accepted.

('RS256',)
leeway float

Seconds of clock skew tolerated.

0.0
timeout float

Seconds before a back-channel request fails.

5.0
token_endpoint_auth_method str

How the client authenticates at the token endpoint.

'client_secret_basic'
rp_initiated_logout bool

Whether :meth:logout_redirect returns the provider's end_session_endpoint. Ignored for an OAuth 2.0 provider, which has none.

False
endpoints OAuth2Endpoints | None

When given, makes an OAuth 2.0 provider; see :meth:oauth2.

None
subject_field str

The user-endpoint member that is the subject.

'sub'
response_issuer str | None

The iss an OAuth 2.0 authorization response must carry; None skips the check.

None

Attributes:

Name Type Description
id

The provider ID.

kind ProviderKind

"oidc", or "oauth2" for an OAuth 2.0 provider.

begin(request, *, return_to)

Return the authorization redirect and the transaction to persist.

Raises:

Type Description
TokenVerificationError

Discovery failed or lacks an endpoint.

complete(request, transaction)

Validate the callback in request against transaction.

Raises:

Type Description
LoginFailed

access_denied when the provider reported error=access_denied; login_failed for every other failure. The reason is for logs.

logout_redirect(session, *, post_logout_redirect)

Return the provider's RP-initiated logout URL, if enabled.

The URL is the discovered end_session_endpoint with id_token_hint (the session's ID token), post_logout_redirect_uri and client_id.

Returns:

Type Description
str | None

The URL, or None when RP-initiated logout is not enabled, the

str | None

provider is OAuth 2.0, the provider advertises no

str | None

end_session_endpoint or the session kept no ID token.

oauth2(*, id, issuer, endpoints, client_id, client_secret, redirect_uri, scopes=(), subject_field='sub', response_issuer=None, claim_mapper=default_claim_mapper, token_hook=None, timeout=5.0, token_endpoint_auth_method='client_secret_basic') classmethod

Build a provider for an OAuth 2.0 server that issues no ID token.

The flow keeps state and PKCE and sends no nonce. After the code exchange the user endpoint is called with the access token; its JSON object is the claim set, with iss set to issuer and sub set to the subject_field member as a string (numbers are stringified), then passed to claim_mapper.

Parameters:

Name Type Description Default
id str

The provider ID.

required
issuer str

The fixed issuer of the identities.

required
endpoints OAuth2Endpoints

The provider's endpoints.

required
client_id str

The registered client.

required
client_secret str | None

The client's secret; None for a public client.

required
redirect_uri str

The registered callback URL.

required
scopes Sequence[str]

The requested scopes.

()
subject_field str

The user-endpoint member that is the subject, such as "id".

'sub'
response_issuer str | None

The iss the authorization response must carry; None skips the check, as for a provider that sends none.

None
claim_mapper ClaimMapper

Replaces :func:default_claim_mapper.

default_claim_mapper
token_hook TokenHook | None

Called with the identity and the upstream tokens.

None
timeout float

Seconds before a back-channel request fails.

5.0
token_endpoint_auth_method str

How the client authenticates at the token endpoint.

'client_secret_basic'

TokenVerificationError(message, *message_args, error_code=-1, **error_data)

Bases: AppException

A token, a key set or a discovery document failed verification.

The message says why. It is for logs: a 401 body must not repeat it.

check(value, message, *message_args, **kwargs) classmethod

Raise this exception if value is falsy.

Parameters:

Name Type Description Default
value Any

The value to test.

required
message str

Exception message (supports positional format args).

required
*message_args Any

Forwarded to message.format().

()
**kwargs Any

Forwarded as error_code / error_data to the constructor.

{}

Example::

AppException.check(path.exists(), "Missing file: {}", path, error_code=404)

UpstreamTokens(access_token, id_token=None, refresh_token=None, scope=None) dataclass

The tokens the provider returned from the code exchange.

Attributes:

Name Type Description
access_token str

The access token.

id_token str | None

The verified ID token; None for an OAuth 2.0 provider.

refresh_token str | None

The refresh token, if issued.

scope str | None

The granted scope, if the provider reported it.

default_claim_mapper(provider, claims)

Map standard OIDC claims to an :class:~rn_forge.auth.ExternalIdentity.

sub, email, email_verified, name, picture, groups, auth_time and amr fill the fields of the same name, and sid fills session_ref. A claim of the wrong type is ignored. Every other claim except the token-protocol ones (iss, aud, exp, iat, nbf, jti, nonce, at_hash, c_hash, azp) goes to attributes.

Raises:

Type Description
LoginFailed

sub or iss is missing.

discover_oidc(issuer, *, fetch=fetch_json)

Read issuer's /.well-known/openid-configuration.

Per RFC 8414 §3.3, the document's issuer must equal the issuer it was fetched for; a mismatch is an error.

Raises:

Type Description
TokenVerificationError

The document is unreachable, lacks issuer or jwks_uri, or names a different issuer.

fetch_json(url, *, timeout=5.0)

GET url and return its JSON object body.

Raises:

Type Description
TokenVerificationError

The URL is not HTTPS (or HTTP to a local host), the request fails, or the body is not a JSON object.