Skip to content

Claims Validation

Injectable, composable validators that run after the standard token checks (signature, iss, aud, exp, nbf) pass. They let you assert application-specific requirements — required claims, exact values, granted scopes — as small, reusable pieces you compose together.

A claims validator is any callable (claims) -> None that raises to reject. That's the whole contract, so a plain function still works:

from py_identity_model import TokenValidationConfig

def require_tenant(claims) -> None:
    if "tenant_id" not in claims:
        raise ValueError("token is missing tenant_id")

config = TokenValidationConfig(
    perform_disco=True,
    issuer="https://issuer.example.com",
    audience="my-api",
    claims_validator=require_tenant,
)

Ready-made validators

require_claims, require_claim_value, and require_scopes cover the common cases and raise a typed ClaimsValidationError that carries a structured reason (and the offending claim) — the reason survives to the caller instead of being flattened to a generic string.

from py_identity_model import require_claims, require_claim_value, require_scopes

require_claims("sub", "email")           # every listed claim must be present (non-null)
require_claim_value("token_use", "access")  # claim must be present AND equal
require_scopes("orders:read", "orders:write")  # from the `scope` string or `scp` array

require_scopes reads scopes from the space-delimited scope claim or the scp array, and fails closed: a malformed (non-string, non-array) scope claim yields no scopes and rejects rather than crashing.

Composing validators

combine_claims_validators merges several into one:

  • require="all" (default) — every validator must accept; fails fast on the first rejection.
  • require="any" — passes if at least one accepts; if all reject, it aggregates their reasons. An empty any-of set is rejected at construction (it could never be satisfied).
from py_identity_model import (
    TokenValidationConfig,
    combine_claims_validators,
    require_claim_value,
    require_scopes,
)

validator = combine_claims_validators(
    [
        require_claim_value("token_use", "access"),
        require_scopes("orders:read"),
    ]
)  # require="all"

config = TokenValidationConfig(
    perform_disco=True,
    issuer="https://issuer.example.com",
    audience="orders-api",
    claims_validator=validator,
)

Because the composed result is itself a plain (claims) -> None callable, it drops straight into the FastAPI middleware / WebSocket authenticator's custom_claims_validator with no adapter.

Construction errors and edge cases

Impossible validators are rejected at construction (ValueError), not at validation time: require_claims() / require_scopes() with zero arguments, combine_claims_validators with require="any" and no members, or a require value other than "all" / "any".

In "any" mode, only a ClaimsValidationError counts as a clean rejection to aggregate — any other exception from a member propagates immediately. Composed members must be synchronous (the combined validator works in both the sync and async validation paths); composing async validators is not supported.

Backward compatibility

This is a pure opt-in layer. Any existing (claims) -> None callable that rejects by raising continues to work exactly as before; only a validator that raises ClaimsValidationError gets its structured reason preserved.

API

ClaimsValidator

Bases: Protocol

A callable that validates decoded token claims.

Called with the decoded claims mapping after the standard checks pass. Return None to accept; raise :class:ClaimsValidationError to reject (any other exception is treated as a programming error and surfaces as a generic validation failure).

claims is positional-only, so a validator may name its parameter anything — the library always calls it positionally.

ClaimsValidationError(reason, *, claim=None)

Bases: TokenValidationException

Raised by a claims validator to reject a token's claims.

Carries a structured reason (and optionally the offending claim) so callers — and the token validators — can surface why without parsing a message string. It is a :class:TokenValidationException, so the existing except TokenValidationException handlers catch it unchanged.

combine_claims_validators(validators, *, require='all')

Compose validators into a single claims validator.

Parameters:

Name Type Description Default
validators Iterable[ClaimsValidator]

The validators to combine (evaluated in order).

required
require Literal['all', 'any']

"all" (default) — every validator must accept; the combined validator raises the first :class:ClaimsValidationError (fail fast). "any" — at least one validator must accept; the combined validator raises a :class:ClaimsValidationError aggregating every reason only if all of them reject.

'all'

Returns:

Type Description
ClaimsValidator

A single (claims) -> None validator.

Raises:

Type Description
ValueError

If require="any" is given no validators — an empty any-of set can never be satisfied, so it would reject every token (guarded like the middleware's empty-marker check). An empty require="all" set is a no-op (accept), which is harmless.

Note

In any mode only a :class:ClaimsValidationError counts as a rejection worth trying the next validator for; any other exception (including a non-ClaimsValidationError TokenValidationException) propagates immediately rather than being aggregated — a "clean reject" is specifically a ClaimsValidationError.

Members must be synchronous. The resulting validator is synchronous and works in both the sync and async token-validation paths. Composing async validators is not yet supported.

require_claims(*names)

A validator that rejects unless every named claim is present (non-null).

require_claim_value(name, value)

A validator that rejects unless claim name is present and equals value.

An absent claim always rejects — including when value is None, so require_claim_value("x", None) means "x must be present and null", not "x may be missing" (a fail-open a plain .get() != value would allow).

require_scopes(*scopes)

A validator that rejects unless the token grants every named scope.

Reads OAuth 2.0 scopes from the scope (space-delimited string) or scp (array) claim.