Skip to content

Token Validation

JWT validation with optional OpenID Connect auto-discovery.

Configuration

TokenValidationConfig(perform_disco, key=None, audience=None, algorithms=None, issuer=None, subject=None, options=None, claims_validator=None, require_https=True, leeway=None, allowed_issuers=None, discovery_policy=None) dataclass

Configuration for JWT token validation.

Attributes:

Name Type Description
perform_disco bool

Whether to perform discovery to fetch JWKS and issuer

key dict | JsonWebKey | None

Public key for JWT verification (manual mode, perform_disco=False). Accepts either a :class:JsonWebKey — exactly what get_jwks returns, so a key can round-trip straight back in — or a plain JWK dict ({"kty": "RSA", "n": ..., "e": ...}). None-valued members are ignored during conversion, so a public key is never misclassified as private.

audience str | None

Expected audience claim(s) in the token

algorithms list[str] | None

List of allowed signing algorithms (e.g., ['RS256'])

issuer str | list[str] | None

Expected issuer claim. A single string or a list of accepted issuers for multi-tenant validation.

subject str | None

Expected sub claim. Validated after decoding.

options dict | None

Additional PyJWT decode options (e.g., {'require': ['sub']}). Security-critical options (verify_signature, verify_exp, verify_nbf, verify_iat) cannot be disabled and will raise ConfigurationException if set to False.

claims_validator Callable | None

Optional injectable claims validator, run after the standard checks pass. A ClaimsValidator is any callable (claims) -> None — sync, or async in the async context — that raises ClaimsValidationError (carrying a structured reason/claim) to reject. The decoded claims dict is passed as the only argument. Any raised exception rejects the token; a ClaimsValidationError (or any TokenValidationException) propagates with its reason intact, other exceptions become a generic failure. Compose several with combine_claims_validators and reuse require_claims / require_claim_value / require_scopes.

leeway float | None

Clock skew tolerance in seconds for exp and nbf claims. Useful when clocks between the issuer and this server are not perfectly synchronized.

allowed_issuers list[str] | None

Optional allowlist of approved issuer identifiers. Purely opt-in. When None (the default) discovery is assumed authoritative and its issuer is used as-is — default behaviour is unchanged. When set, the issuer used to validate the token (the discovery document's issuer in discovery mode, otherwise issuer) MUST be a member, checked before the discovery result is trusted. Set it only for multi-tenant callers that resolve discovery from an untrusted token's iss — without it an attacker who stands up their own tenant and mints a validly-signed token would pass validation.

discovery_policy DiscoveryPolicy | None

Optional :class:DiscoveryPolicy applied to the discovery document (and its advertised endpoints) on the cached validate_token path. When None (the default) a policy is derived from require_https alone — behaviour is unchanged. Set it to reach any of the other policy knobs (validate_issuer, validate_endpoints, additional_endpoint_base_addresses, authority, allow_loopback_endpoints, allow_http_on_loopback) while still using the built-in discovery/JWKS TTL cache, instead of calling get_discovery_document directly and re-implementing caching. When provided, discovery_policy takes precedence over require_https (the policy's own require_https governs). The discovery cache is partitioned by the full policy, so a response admitted under a lax policy is never served to a stricter caller.

Examples:

>>> # Multi-tenant with clock skew tolerance
>>> config = TokenValidationConfig(
...     perform_disco=True,
...     audience="my-api",
...     issuer=[
...         "https://idp1.example.com",
...         "https://idp2.example.com",
...     ],
...     leeway=30,
... )
>>> # Custom claims validation
>>> def validate_custom_claims(claims: dict) -> None:
...     if claims.get("role") != "admin":
...         raise ValueError("User is not an admin")
>>>
>>> config = TokenValidationConfig(
...     perform_disco=True,
...     claims_validator=validate_custom_claims,
... )

Sync API

validate_token(jwt, token_validation_config, disco_doc_address=None, http_client=None)

Validate a JWT token.

Parameters:

Name Type Description Default
jwt str

The JWT token to validate

required
token_validation_config TokenValidationConfig

Token validation configuration

required
disco_doc_address str | None

Discovery document address (required if perform_disco=True)

None
http_client HTTPClient | None

Optional managed HTTP client. When None (the default), uses the thread-local default with the full TTL cache + cooldown stack. When provided, all of the following are bypassed:

  • Discovery document cache — every call re-fetches the .well-known/openid-configuration document.
  • JWKS cache — every call re-fetches the JWKS.
  • Kid-miss cooldown — an attacker forging tokens with unknown kid headers drives 1:1 upstream JWKS fetches with no rate limit.
  • Signature-failure cooldown — an attacker forging signatures against cached kids drives 1:1 upstream JWKS fetches on the retry path with no rate limit.

The injected-client path is appropriate for one-off validations (CLI tooling, tests) and for callers that have implemented their own caching layer over the HTTP client. It is not appropriate for high-volume request paths exposed to untrusted JWTs.

A logger.warning is emitted the first time an injected client is used in the process so accidental opt-out is detectable in production logs.

None

Returns:

Name Type Description
dict dict

Decoded token claims

Raises:

Type Description
TokenValidationException

If token validation fails

ConfigurationException

If configuration is invalid

Async API

validate_token(jwt, token_validation_config, disco_doc_address=None, http_client=None) async

Validate a JWT token (async).

Parameters:

Name Type Description Default
jwt str

The JWT token to validate

required
token_validation_config TokenValidationConfig

Token validation configuration

required
disco_doc_address str | None

Discovery document address (required if perform_disco=True)

None
http_client AsyncHTTPClient | None

Optional managed HTTP client. When None (the default), uses the module-level singleton with the full TTL cache + cooldown stack. When provided, all of the following are bypassed:

  • Discovery document cache — every call re-fetches the .well-known/openid-configuration document.
  • JWKS cache — every call re-fetches the JWKS.
  • Kid-miss cooldown — an attacker forging tokens with unknown kid headers drives 1:1 upstream JWKS fetches with no rate limit.
  • Signature-failure cooldown — an attacker forging signatures against cached kids drives 1:1 upstream JWKS fetches on the retry path with no rate limit.

The injected-client path is appropriate for one-off validations (CLI tooling, tests) and for callers that have implemented their own caching layer over the HTTP client. It is not appropriate for high-volume request paths exposed to untrusted JWTs.

A logger.warning is emitted the first time an injected client is used in the process so accidental opt-out is detectable in production logs.

None

Returns:

Name Type Description
dict dict

Decoded token claims

Raises:

Type Description
TokenValidationException

If token validation fails

ConfigurationException

If configuration is invalid