Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

py-identity-model

Build License

Production-grade OIDC/OAuth2.0 client library for Python. Dual sync/async API with comprehensive RFC coverage. Inspired by Duende.IdentityModel.

OpenID Certified

OpenID Certified

py-identity-model is OpenID Certified® by the OpenID Foundation as a Relying Party (RP) for the Basic RP, Config RP, and Form Post Basic RP conformance profiles (certified 2 July 2026, py-identity-model 3.1.0). See the certification docs for the conformance harness and submission process.

OpenID Certified is a certification mark of the OpenID Foundation.

Installation

pip install py-identity-model

Or with uv:

uv add py-identity-model

Requirements: Python 3.12+

Features

Protocol Support

Feature RFC/Spec Status
OpenID Connect Discovery 1.0 OIDC Discovery Done
JSON Web Key Sets RFC 7517 Done
JWT Validation RFC 7519 Done
Client Credentials Grant RFC 6749 Done
Authorization Code + PKCE RFC 7636 Done
Refresh Token Grant RFC 6749 Done
Token Introspection RFC 7662 Done
Token Revocation RFC 7009 Done
Device Authorization RFC 8628 Done
Token Exchange RFC 8693 Done
DPoP RFC 9449 Done
Pushed Authorization Requests RFC 9126 Done
JWT Secured Authorization Request RFC 9101 Done
JWT Secured Authorization Response Mode (JARM) JARM Done
private_key_jwt Client Authentication RFC 7523 Done
Mutual-TLS Client Auth + Certificate-Bound Tokens RFC 8705 Done
FAPI 2.0 Security Profile FAPI 2.0 Done
UserInfo Endpoint OIDC Core Done
OAuth Callback State Validation RFC 6749 Done
AS Issuer Identification (Mix-Up Defense) RFC 9207 Done
Policy-Based Configuration — Done

Architecture

  • Dual API: Synchronous (py_identity_model) and asynchronous (py_identity_model.aio)
  • Thread-safe: Sync uses thread-local HTTP clients; async uses singleton with lock protection
  • Modular: Shared business logic in core/, thin sync/async HTTP wrappers
  • Connection pooling: httpx-based with configurable timeouts and retry logic

Quick Start

Discovery

from py_identity_model import DiscoveryDocumentRequest, get_discovery_document

response = get_discovery_document(DiscoveryDocumentRequest(issuer="https://issuer.example.com"))
if response.is_successful:
    print(f"Token Endpoint: {response.token_endpoint}")

Token Validation

from py_identity_model import TokenValidationConfig, validate_token

config = TokenValidationConfig(perform_disco=True, audience="my-api")
claims = validate_token(jwt=token, token_validation_config=config, issuer="https://issuer.example.com")

Async API

from py_identity_model.aio import get_discovery_document, validate_token
from py_identity_model import DiscoveryDocumentRequest

response = await get_discovery_document(DiscoveryDocumentRequest(issuer=issuer))

Client Credentials

from py_identity_model import (
    ClientCredentialsTokenRequest,
    request_client_credentials_token,
)

token = request_client_credentials_token(ClientCredentialsTokenRequest(
    client_id="my-client", client_secret="secret",
    address=token_endpoint, scope="api"
))

Examples

Each protocol feature has a standalone example in examples/:

Example Feature
sync_examples.py Discovery, JWKS, token validation, client credentials
async_examples.py Async versions of all core operations
auth_code_pkce_example.py Authorization Code + PKCE flow
introspection_example.py Token introspection (RFC 7662)
revocation_example.py Token revocation (RFC 7009)
dpop_example.py DPoP proof creation (RFC 9449)
par_example.py Pushed Authorization Requests (RFC 9126)
jar_example.py JWT Secured Authorization Request (RFC 9101)
jarm_example.py JWT Secured Authorization Response Mode (JARM)
private_key_jwt_example.py private_key_jwt client authentication (RFC 7523)
mtls_example.py mTLS client auth + certificate-bound tokens (RFC 8705)
fapi_example.py FAPI 2.0 Security Profile
device_auth_example.py Device Authorization Grant (RFC 8628)
token_exchange_example.py Token Exchange (RFC 8693)

Framework Integration

py-identity-model is framework-agnostic — call validate_token (or py_identity_model.aio.validate_token) from any Python framework's auth layer. For FastAPI, examples/fastapi/ ships a complete, production-shaped integration you can copy into your own project:

  • TokenValidationMiddleware — Bearer token extraction, JWKS-cached validation, configurable excluded paths, pluggable custom-claim validators
  • Dependency injection — CurrentUser, Claims, Token annotated types for typed access to the authenticated principal from route handlers
  • Authorization guards — require_claim(type, value) and require_scope(scope) factories that plug into Depends(...) to enforce RBAC/ABAC at the route level
  • Token refresh helper — Proactive refresh of expiring access tokens for service-to-service flows
from fastapi import Depends, FastAPI

from .middleware import TokenValidationMiddleware
from .dependencies import CurrentUser, require_scope

app = FastAPI()

app.add_middleware(
    TokenValidationMiddleware,
    issuer="https://issuer.example.com",
    audience="my-api",
    excluded_paths=["/health", "/docs", "/openapi.json"],
)


@app.get("/me")
async def me(user: CurrentUser) -> dict:
    return {"sub": user.identity.name}


@app.get("/admin", dependencies=[Depends(require_scope("api.admin"))])
async def admin() -> dict:
    return {"status": "ok"}
Integration Path Highlights
FastAPI examples/fastapi/ Middleware, DI, authorization guards, token refresh
Descope (FastAPI) examples/descope/ Extends the FastAPI base with Descope-specific issuer/tenant handling

Configuration

Settings are passed in; the library reads no environment variables. Build an HTTPConfig and pass it on an HTTP client, then pass the client to any entry point (cache settings go on a CacheConfig, passed on a ValidationCache):

from py_identity_model import HTTPClient, HTTPConfig, validate_token

client = HTTPClient(config=HTTPConfig(http_timeout=10.0, ca_bundle="/path/to/ca.crt"))
claims = validate_token(token, validation_config, issuer, http_client=client)

Without http_client=, the library default client (built from HTTPConfig()) is used. To read the settings from environment variables (HTTP_TIMEOUT, HTTP_RETRY_COUNT, SSL_CERT_FILE, ...), call the optional helpers py_identity_model.config_helpers.http_config_from_env() and cache_config_from_env(). Every setting and its default is listed in the Configuration reference.

Documentation

Full docs: jamescrowley321.github.io/identity-model

License

Apache License 2.0

Metadata

Release files for py-identity-model 5.0.0a1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-identity-model 5.0.0a1
File Size Uploaded Provenance Actions
py_identity_model-5.0.0a1.tar.gz 241.0 kB Without provenance Details for py_identity_model-5.0.0a1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for py-identity-model 5.0.0a1
File Interpreter ABI Platform Actions
py_identity_model-5.0.0a1-py3-none-any.whl Python 3 none any Details for py_identity_model-5.0.0a1-py3-none-any.whl

Total release size: 524.6 kB

Release files / py_identity_model-5.0.0a1.tar.gz

Download URL py_identity_model-5.0.0a1.tar.gz
Size 241.0 kB
Tags Source
SHA-256 checksum
How to use checksums
1e8faff42e71078f29f6b85f1a8d6cce5ffbddcc740a6e892308a8e922baa902
BLAKE2b-256 checksum
How to use checksums
c3296972e6c3ad2aee3eb16b4cf7dac79c0a3e97d3f7422de2ac6a814bb93f6d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / py_identity_model-5.0.0a1-py3-none-any.whl

Download URL py_identity_model-5.0.0a1-py3-none-any.whl
Size 283.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fda2b120aa2f32e0c6c38db61347147cdc067abcb718f5cf84d14ad1c9cce50a
BLAKE2b-256 checksum
How to use checksums
905622121462ba8c948ab7068c918e9a799b682840a336f9259a3f6c67493426
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for py-identity-model 5.0.0a1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page