Mutual TLS (mTLS)¶
OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens (RFC 8705): authenticate the client with an X.509 certificate at the TLS layer instead of a shared secret, and verify that an access token is bound to the certificate that requested it.
Client authentication¶
Attach an MtlsClientAuth to
any client-authenticating request (ClientCredentialsTokenRequest,
AuthorizationCodeTokenRequest, RefreshTokenRequest, introspection,
revocation, PAR, device, token-exchange, and UserInfo requests) via its mtls
field. The certificate is presented during the TLS handshake, client_id goes
in the request body, and no Authorization header is sent (RFC 8705 §2).
When both are present, private_key_jwt takes precedence over mtls, which
takes precedence over client_secret.
from py_identity_model import (
ClientCredentialsTokenRequest,
DiscoveryDocumentRequest,
MtlsClientAuth,
get_discovery_document,
request_client_credentials_token,
resolve_mtls_endpoint,
)
disco = get_discovery_document(DiscoveryDocumentRequest(address=DISCOVERY_URL))
# Prefer the mTLS alias of the endpoint when the AS advertises one (§5).
token_endpoint = resolve_mtls_endpoint(disco, "token_endpoint")
response = request_client_credentials_token(
ClientCredentialsTokenRequest(
address=token_endpoint,
client_id="my-mtls-client",
scope="api",
mtls=MtlsClientAuth(
certificate="/path/to/client-cert.pem",
private_key="/path/to/client-key.pem",
auth_method="self_signed_tls_client_auth",
),
)
)
An mtls value cannot be combined with a caller-managed http_client on the
same request — a managed client cannot be guaranteed to present the
certificate, so supplying both is rejected rather than silently sending an
unauthenticated request.
Certificate-bound access tokens¶
A resource server verifying a certificate-bound token compares the token's
cnf["x5t#S256"] confirmation claim against the thumbprint of the certificate
the client presented at the TLS layer. validate_certificate_binding performs
that comparison in constant time — call it after normal signature and
time validation:
from py_identity_model import (
CertificateBindingError,
TokenValidationConfig,
validate_certificate_binding,
validate_token,
)
claims = validate_token(token, TokenValidationConfig(perform_disco=True, audience="api"), DISCOVERY_URL)
try:
validate_certificate_binding(claims, presented_cert_pem)
except CertificateBindingError:
... # token is bound to a different certificate — reject the request
CertificateBindingError subclasses
TokenValidationException, so existing except TokenValidationException
handlers fail closed on a binding mismatch.
API¶
Client authentication¶
MtlsClientAuth(certificate, private_key, password=None, auth_method='tls_client_auth')
dataclass
¶
Mutual-TLS client authentication parameters (RFC 8705).
When supplied on a client-authenticating request, the client is
authenticated by presenting an X.509 certificate at the TLS layer
(tls_client_auth or self_signed_tls_client_auth) instead of a
client secret. client_id is carried in the request body and no
Authorization header is sent (RFC 8705 §2). It takes precedence over
client_secret but sits below private_key_jwt when both are present.
The certificate is presented at the TLS layer, so the sync/async HTTP wrappers build a short-lived, cert-configured client for the request.
Attributes:
| Name | Type | Description |
|---|---|---|
certificate |
str
|
Filesystem path to the PEM-encoded client certificate. |
private_key |
str
|
Filesystem path to the PEM-encoded private key. |
password |
str | None
|
Optional password for an encrypted private key. Secret —
|
auth_method |
str
|
The RFC 8705 §2 method name — |
resolve_mtls_endpoint(disco, endpoint)
¶
Resolve endpoint through mtls_endpoint_aliases when advertised.
Per RFC 8705 §5, an authorization server may advertise mTLS-specific
endpoint URLs in mtls_endpoint_aliases. When a matching alias exists
for endpoint, it is returned; otherwise endpoint is returned unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
disco
|
DiscoveryDocumentResponse
|
The authorization server's discovery document. |
required |
endpoint
|
str
|
The endpoint name to resolve (e.g. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
The mTLS endpoint URL alias when present, else the standard endpoint |
str | None
|
URL from the discovery document ( |
Certificate binding¶
validate_certificate_binding(claims, cert)
¶
Validate an RFC 8705 §3 certificate-bound access token confirmation.
Confirms the token's cnf["x5t#S256"] confirmation method matches the
SHA-256 thumbprint of the client certificate presented at the TLS layer.
The comparison is constant-time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
claims
|
dict
|
Decoded access-token claims (must already be signature- and time-validated by the caller). |
required |
cert
|
str | bytes
|
The client certificate presented on the mTLS connection — PEM
( |
required |
Raises:
| Type | Description |
|---|---|
CertificateBindingError
|
If the |
ValueError
|
If cert is empty or not a valid certificate. |
compute_certificate_thumbprint(cert)
¶
Compute the RFC 8705 §3.1 x5t#S256 certificate thumbprint.
The value is the base64url-encoded (no padding) SHA-256 hash of the
certificate's DER encoding, matching the cnf["x5t#S256"] member of a
certificate-bound access token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cert
|
str | bytes
|
Client certificate content — PEM ( |
required |
Returns:
| Type | Description |
|---|---|
str
|
The base64url-no-pad SHA-256 thumbprint string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If cert is empty or not a valid certificate. |
certificate_thumbprint_from_file(path)
¶
Compute the x5t#S256 thumbprint of a certificate file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Filesystem path to a PEM- or DER-encoded certificate. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The base64url-no-pad SHA-256 thumbprint string. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If path is empty or the file is not a valid certificate. |
OSError
|
If the file cannot be read. |
Exceptions¶
CertificateBindingError(message, details=None)
¶
Bases: TokenValidationException
Raised when mTLS certificate-bound access token validation fails.
Covers the RFC 8705 §3 confirmation-method check: the token's
cnf["x5t#S256"] thumbprint must match the client certificate
presented at the TLS layer. Absent cnf/x5t#S256 or a thumbprint
mismatch raises this error.
Subclasses TokenValidationException (not ValidationException
directly): a certificate-binding failure is a token-validation failure,
so callers using the idiomatic except TokenValidationException must
fail closed on it. As a sibling it would escape that handler and
fail open — the exact replay it is meant to stop.