Skip to main content

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>
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 Bearer tokens

from fastapi import FastAPI, Depends
from fastapi_identity_model import (
    TokenValidationMiddleware, OIDCSettings, get_current_user, require_scope,
)

settings = OIDCSettings.from_env()  # OIDC_DISCOVERY_URL, OIDC_CLIENT_ID, OIDC_REDIRECT_URI, ...
app = FastAPI()
app.add_middleware(
    TokenValidationMiddleware,
    discovery_url=settings.discovery_url,
    audience=settings.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"}

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).

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(
    discovery_url="https://api.descope.com/v1/apps/<project_id>/.well-known/openid-configuration",
    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.

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.

Token refresh

from fastapi_identity_model import TokenManager

tm = TokenManager(discovery_url=..., client_id=..., client_secret=...)
tm.set_tokens(access_token=..., refresh_token=..., expires_in=3600)
access = await tm.get_access_token()   # auto-refreshes shortly before expiry

License

Apache-2.0 — see the repository LICENSE.

Metadata

Release files for fastapi-identity-model 0.2.3

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

Source distribution (sdist)

Source distribution for fastapi-identity-model 0.2.3
File Size Uploaded Provenance Actions
fastapi_identity_model-0.2.3.tar.gz 29.5 kB Without provenance Details for fastapi_identity_model-0.2.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-identity-model 0.2.3
File Interpreter ABI Platform Actions
fastapi_identity_model-0.2.3-py3-none-any.whl Python 3 none any Details for fastapi_identity_model-0.2.3-py3-none-any.whl

Total release size: 49.6 kB

Release files / fastapi_identity_model-0.2.3.tar.gz

Download URL fastapi_identity_model-0.2.3.tar.gz
Size 29.5 kB
Tags Source
SHA-256 checksum
How to use checksums
f3cae399ac6503daf23c64ac2c1155fb3ec5cc5c98a0abdd6c1a3a27fce01be6
BLAKE2b-256 checksum
How to use checksums
cb505c000cc0c982074c021f7856d7f7ed669877e1ea7992a97f1fce8cd87a2e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.9 {"installer":{"name":"uv","version":"0.12.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","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.2.3-py3-none-any.whl

Download URL fastapi_identity_model-0.2.3-py3-none-any.whl
Size 20.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e754ed87467811360c4fafb0b3cf4a9107b6cf6345270f404b768d306ff437c3
BLAKE2b-256 checksum
How to use checksums
9413bef647e94f6223d2b679970408f577e0b4467e5a8fa405cb5e54da1e65a6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.12.9 {"installer":{"name":"uv","version":"0.12.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","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.2.3

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.

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