This release is a pre-release and may not be stable for production use.
fastapi-identity-model
OIDC/OAuth2 integration for FastAPI, built on
py-identity-model — an OpenID
Foundation–certified relying-party library.
It gives you two composable pieces:
| Piece | Use case |
|---|---|
TokenValidationMiddleware + Depends helpers |
Protect an API / resource server that receives Authorization: Bearer <token> or Authorization: DPoP <token> |
build_oidc_router |
Add a browser login flow (authorization code + PKCE) to your app (relying party) |
Install
pip install fastapi-identity-model
# with a server for the demo:
pip install "fastapi-identity-model[server]"
Resource server — validate incoming access tokens
from fastapi import FastAPI, Depends
from fastapi_identity_model import (
TokenValidationMiddleware, OIDCSettings, get_current_user, require_scope,
)
settings = OIDCSettings(
issuer="https://op.example.com",
client_id="<client_id>",
)
app = FastAPI()
app.add_middleware(
TokenValidationMiddleware,
issuer=settings.issuer,
audience=settings.expected_audience,
excluded_paths=settings.excluded_paths,
)
@app.get("/api/me")
async def me(user = Depends(get_current_user)):
return {"sub": user.identity.name, "authenticated": user.identity.is_authenticated}
@app.get("/api/data", dependencies=[Depends(require_scope("api.read"))])
async def data():
return {"data": "protected"}
issuer is the provider's issuer identifier, not its discovery URL. The
discovery document is fetched from <issuer>/.well-known/openid-configuration,
and its issuer and each token's iss must equal the configured value
exactly (https://op.example.com and https://op.example.com/ are different
issuers). A value ending with /.well-known/... is a configuration error.
The middleware validates the token (signature, issuer, audience, expiry) via
py-identity-model and attaches a ClaimsPrincipal to request.state.user.
Invalid tokens → 401; an unexpected server-side failure → 500 (never
masked as a 401).
Sender-constrained tokens are always checked: a DPoP-bound token (cnf.jkt)
needs the DPoP scheme and a valid proof, and a certificate-bound token needs
its client certificate. Binding options live on one AuthOptions, passed as
options= to both TokenValidationMiddleware and build_ws_authenticator;
pass settings= instead to read OIDC_REQUIRED_BINDING and friends from
OIDCSettings. AuthOptions(required_binding=TokenBinding.DPOP) also refuses
unbound tokens. See
DPoP resource server verification.
Relying party — browser login flow
import os
from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware
from fastapi_identity_model import OIDCSettings, build_oidc_router
settings = OIDCSettings(
issuer="https://api.descope.com/v1/apps/<project_id>",
client_id="<client_id>",
redirect_uri="http://localhost:8000/auth/callback",
scope="openid profile email",
)
app = FastAPI()
# Use a strong secret from the environment — never a committed literal, or
# anyone can forge a session cookie. same_site="lax" is required so the
# provider's redirect back to /auth/callback carries the session cookie.
app.add_middleware(
SessionMiddleware,
secret_key=os.environ["SESSION_SECRET"],
same_site="lax",
https_only=True, # behind TLS
)
app.include_router(build_oidc_router(settings), prefix="/auth")
@app.get("/me")
async def me(request: Request):
return request.session.get("oidc", {}) # {"sub", "claims", "userinfo"} after login
Routes added: GET /auth/login → provider, GET /auth/callback (code exchange,
ID-token validation, nonce check, UserInfo sub verification), POST /auth/logout.
The callback validates the ID Token with validate_id_token (OIDC Core
§3.1.3.7). An ID Token whose aud lists anything besides client_id fails
the login unless that audience is in trusted_audiences
(OIDC_TRUSTED_AUDIENCES). If your provider issues multi-audience ID Tokens,
list the extra audiences. Whenever you set OIDC_TRUSTED_AUDIENCES, also set
OIDC_VALIDATE_AZP=true (validate_azp=True), so the token must name your
client as its authorized party (azp). Without it, an ID Token issued to
another client that also lists yours in aud logs in. The azp check is off
by default because OIDC Core §3.1.3.7 makes it a SHOULD:
settings = OIDCSettings(
...,
trusted_audiences=["https://api.example.com"],
validate_azp=True,
)
Session & security
The router uses Starlette's SessionMiddleware, which signs but does not
encrypt the cookie. Stored identity claims are tamper-proof but readable by the
client. Raw tokens are stored only when you pass build_oidc_router(settings, store_tokens=True) — enable that only with an encrypted or server-side session
store. For production, back the session with a server-side store.
Configuration
The package reads no environment variables. Construct OIDCSettings yourself,
or build it from the environment with the optional helper:
from fastapi_identity_model.config_helpers import oidc_settings_from_env
settings = oidc_settings_from_env() # OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_REDIRECT_URI, ...
settings = oidc_settings_from_env("APP_") # APP_ISSUER, APP_CLIENT_ID, ...
ISSUER and CLIENT_ID are required. EXCLUDED_PATHS and
TRUSTED_AUDIENCES are comma-separated lists; an empty TRUSTED_AUDIENCES
entry raises ValueError. VALIDATE_AZP is true or false. Every other variable (REDIRECT_URI, CLIENT_SECRET,
SCOPE, AUDIENCE, POST_LOGIN_REDIRECT, POST_LOGOUT_REDIRECT) falls back
to the OIDCSettings default when unset. AUDIENCE sets audience_override;
read the audience to check from settings.expected_audience.
HTTP settings belong to a py-identity-model HTTPConfig, and cache settings
to a CacheConfig. Build an AsyncHTTPClient from the first (timeouts,
retries, CA bundle) and pass it as
http_client= to TokenValidationMiddleware, build_oidc_router,
build_ws_authenticator and TokenManager. Without it, the library default
client is used.
The discovery document, the keys and the kid-miss cooldown are kept on an
AsyncValidationCache, not on the client. Pass one as cache= to
TokenValidationMiddleware and build_ws_authenticator to set the cache
TTLs, size or cooldown. Without it, and in build_oidc_router, the library
default cache is used.
from py_identity_model import CacheConfig, HTTPConfig
from py_identity_model.aio import AsyncHTTPClient, AsyncValidationCache
http_client = AsyncHTTPClient(config=HTTPConfig(http_timeout=10.0))
cache = AsyncValidationCache(config=CacheConfig(jwks_cache_ttl=900.0))
app.add_middleware(
TokenValidationMiddleware,
issuer=settings.issuer,
audience=settings.expected_audience,
http_client=http_client,
cache=cache,
)
app.include_router(build_oidc_router(settings, http_client=http_client), prefix="/auth")
Close the client on shutdown (await http_client.close(), e.g. in the app's
lifespan). A cache holds no connections and needs no closing.
Token refresh
from fastapi_identity_model import TokenManager
tm = TokenManager(issuer=..., client_id=..., client_secret=...)
tm.set_tokens(
access_token=..., refresh_token=..., expires_in=3600, token_type="Bearer"
)
access = await tm.get_access_token() # auto-refreshes shortly before expiry
headers = {"Authorization": f"{tm.token_type.value} {access}"}
token_type is the token response's token_type, matched case-insensitively.
Anything but Bearer or DPoP raises TokenManagerError with
kind=TokenManagerErrorKind.UNSUPPORTED_TOKEN_TYPE. Every failure is a
TokenManagerError whose kind says why: NO_REFRESH_TOKEN,
DISCOVERY_FAILED, REFRESH_FAILED, MISSING_ACCESS_TOKEN or
UNSUPPORTED_TOKEN_TYPE. For an unsuccessful refresh, details["error"]
carries the core library's message verbatim: the status code for an HTTP
failure, a fixed label for network and unexpected errors. The core never
embeds response bodies in these messages — a body may contain secrets even in
error or error_description — so this layer passes them through without
rewriting.
License
Apache-2.0 — see the repository LICENSE.
Metadata
Release files for fastapi-identity-model 0.4.0a1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_identity_model-0.4.0a1.tar.gz | 72.3 kB | Without provenance | Details for fastapi_identity_model-0.4.0a1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_identity_model-0.4.0a1-py3-none-any.whl | Python 3 | none | any | Details for fastapi_identity_model-0.4.0a1-py3-none-any.whl |
Total release size: 113.6 kB
Release files / fastapi_identity_model-0.4.0a1.tar.gz
| Download URL | fastapi_identity_model-0.4.0a1.tar.gz |
|---|---|
| Size | 72.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1f688bb1ef6ea7e3197a7b12e2dbfa0e96c8a50e691d22b2729d0d2008529074
|
|
BLAKE2b-256 checksum How to use checksums |
9de23fae87ad2db02c30379174df22cc6fa209e22a21c26920723daaba14470f
|
| 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 / fastapi_identity_model-0.4.0a1-py3-none-any.whl
| Download URL | fastapi_identity_model-0.4.0a1-py3-none-any.whl |
|---|---|
| Size | 41.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1100e4ee8bdc7e8b22234e6d594d12615f514f24581a52bcae1b92df657ac1cb
|
|
BLAKE2b-256 checksum How to use checksums |
757b15f79df7e5315e7d9d01c98f4afc143492d1ed1394242f2ecd3eed8c9d8f
|
| 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 fastapi-identity-model 0.4.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.