A small, typed OpenID Connect helper for authentication and authorization.
It provides
- a framework independent async core:
OIDCAuth - framework adapters that expose common auth endpoints
- simple
required()andoptional()helpers to protect routes - token minting/brokering and token federation
What it does
py-oidc-auth adds OpenID Connect authentication to your Python web application. You create one auth instance at app startup, get a pre-built router (or blueprint / URL patterns), optionally add your own custom routes to it, and include it in your app. Protected routes use required() and optional() helpers.
Supported frameworks
|
FastAPI |
Flask |
Quart |
|
Tornado |
Litestar |
Django |
Features
- Authorization code flow with client side PKCE (and a legacy server side mode)
- Refresh token flow
- Device authorization flow
- Userinfo lookup
- Provider initiated logout (end session) when supported
- Bearer token validation using provider JWKS, issuer, and audience
- Optional scope checks and simple claim constraints
- Full type annotation 🏷️
Install
Pick your framework for installation with pip:
python -m pip install py-oidc-auth[fastapi]
python -m pip install py-oidc-auth[flask]
python -m pip install py-oidc-auth[quart]
python -m pip install py-oidc-auth[tornado]
python -m pip install py-oidc-auth[litestar]
python -m pip install py-oidc-auth[django]
Or use conda/mamba/micromamba:
conda install -c conda-forge py-oidc-auth-fastapi
conda install -c conda-forge py-oidc-auth-flask
conda install -c conda-forge py-oidc-auth-quart
conda install -c conda-forge py-oidc-auth-tornado
conda install -c conda-forge py-oidc-auth-litestar
conda install -c conda-forge py-oidc-auth-django
Import name is py_oidc_auth:
from py_oidc_auth import OIDCAuth
Concepts
Core
OIDCAuth is the framework independent client. It loads provider metadata from the
OpenID Connect discovery document, performs provider calls, and validates tokens.
Adapters
Each adapter subclasses OIDCAuth and adds:
- helpers to register the standard endpoints (router, blueprint, urlpatterns, etc.)
required()andoptional()helpers to validate bearer tokens on protected routes
Default endpoints
Adapters can expose these paths (customizable and individually disabled):
GET /auth/v2/loginGET /auth/v2/callbackPOST /auth/v2/tokenPOST /auth/v2/deviceGET /auth/v2/logoutGET /auth/v2/userinfoGET /auth/v2/.well-known/jwks.json
PKCE, state and logout
Clients should keep their PKCE verifier to themselves. Make a verifier,
send only its S256 challenge and your own state to the login endpoint,
let the provider redirect to your own callback, check state there and
redeem the code at the token endpoint with the verifier:
GET /auth/v2/login?redirect_uri=http://localhost:53100/callback
&code_challenge=<base64url(sha256(verifier)), no padding>&state=<random>
... browser comes back to http://localhost:53100/callback?code=...&state=...
POST /auth/v2/token code=...&redirect_uri=...&code_verifier=<verifier>
The device flow works the same way: send code_challenge to
POST /auth/v2/device and code_verifier with every poll of the token
endpoint. Keycloak (25 and later) then refuses the device code without the
verifier.
A login without code_challenge still works: the server makes the verifier
and carries it, with the redirect URI, in state for /auth/v2/callback.
That gives no PKCE protection (whoever sees the redirect sees code and
verifier together) and logs a warning. Once your clients send challenges,
set require_client_pkce=True to refuse such logins and device flows, to
refuse codes and device codes redeemed without code_verifier and to
disable /auth/v2/callback. Also set the provider client to require S256
(in Keycloak: client, Advanced, "Proof Key for Code Exchange Code Challenge
Method"), so that codes obtained from the provider directly need a
verifier too.
Token responses carry the provider's id_token (not in broker mode). Pass
it to GET /auth/v2/logout?id_token_hint=... so the provider ends the
session without asking the user to confirm.
The token endpoint takes refresh_token and device_code; the older
refresh-token and device-code still work. When the provider cannot be
reached, the endpoints answer 503; when its discovery URL answers but gives
no discovery document (a wrong URL or realm), they answer 502 with the
reason.
Quick start
Create one auth instance at app startup:
auth = ...(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
FastAPI
from typing import Dict, Optional
from fastapi import FastAPI
from py_oidc_auth import FastApiOIDCAuth, IDToken
app = FastAPI()
auth = FastApiOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
app.include_router(auth.create_auth_router(prefix="/api"))
@app.get("/me")
async def me(token: IDToken = auth.required()) -> Dict[str, str]:
return {"sub": token.sub}
@app.get("/feed")
async def feed(token: Optional[IDToken] = auth.optional() -> Dict[str, str]:
if token is None:
message = "Welcome guest"
else:
message = "Welcome back, {token.given_name}"
return {"message": message}
Flask
from flask import Flask, Response, jsonify
from py_oidc_auth import FlaskOIDCAuth
app = Flask(__name__)
auth = FlaskOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
app.register_blueprint(auth.create_auth_blueprint(prefix="/api"))
@app.get("/protected")
@auth.required()
def protected(token: IDToken) -> Response:
return jsonify({"sub": token.sub})
Quart
from quart import Quart, Response, jsonify
from py_oidc_auth import QuartOIDCAuth, IDToken
app = Quart(__name__)
auth = QuartOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
app.register_blueprint(auth.create_auth_blueprint(prefix="/api"))
@app.get("/protected")
@auth.required()
async def protected(token: IDToken) -> Response:
return jsonify({"sub": token.sub})
Django
Decorator style:
from django.http import HttpRequest, JsonResponse
from django.urls import include, path
from py_oidc_auth import DjangoOIDCAuth, IDToken
auth = DjangoOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
@auth.required()
async def protected_view(request: HttpRequest, token: IDToken) -> JsonResponse:
return JsonResponse({"sub": token.sub})
urlpatterns = [
path("api/", include(auth.get_urlpatterns())),
path("protected/", protected_view),
]
Routes only:
urlpatterns = [
*auth.get_urlpatterns(prefix="api"),
path("api/", include(...))
]
Tornado
import json
import tornado.web
from py_oidc_auth import TornadoOIDCAuth, IDToken
auth = TornadoOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
class ProtectedHandler(tornado.web.RequestHandler):
@auth.required()
async def get(self, token: IDToken) -> None:
self.write(json.dumps({"sub": token.sub}))
def make_app():
return tornado.web.Application(
auth.get_auth_routes(prefix="/api") + [
(r"/protected", ProtectedHandler),
]
)
Litestar
from typing import Dict
from litestar import Litestar, get
from litestar.di import NamedDependency
from py_oidc_auth import IDToken, LitestarOIDCAuth
auth = LitestarOIDCAuth(
client_id="my client",
client_secret="secret",
discovery_url="https://idp.example.org/realms/demo/.well-known/openid-configuration",
scopes="myscope profile email",
audience="my-aud",
broker_mode=True,
broker_store_url="postgresql+asyncpg://user:pw@db/myapp",
broker_audience="myapp-api",
trusted_issuers=["https://other-instance.example.org"],
)
@get("/protected", dependencies={"token": auth.required()})
async def protected(token: NamedDependency[IDToken]) -> Dict[str, str]:
return {"sub": token.sub}
app = Litestar(
route_handlers=[
protected,
auth.create_auth_router(prefix="/api"),
]
)
Scopes audience and claim constraints
All adapters support:
scopes="a b c"to require scopes on a protected endpointclaims={...}to enforce simple claim constraintsaudience=my-audto enforce intended audience check
FastApi Example:
@auth.required(scopes="admin", claims={"groups": ["admins"]})
def admin(token: IDToken) -> Dict[str, str]:
return {"sub": token.sub}
Scope checks also apply in broker mode, where broker tokens carry the scope the Identity Provider granted.
Clients may ask for fewer scopes at login (/login?scope=...), but only narrow
the configured ones: every requested scope must be in scopes, openid,
offline_access or allowed_scopes, otherwise the request is refused (400,
invalid_scope). The Identity Provider still decides what it grants: Keycloak
always adds a client's default client scopes, so a request can only leave out
optional ones.
Token minting and federation
The broker_mode=True option allows for the creation of minting of application
specific tokens rather than passing tokens from the Identity Provider.
Token minting also allows for token federation where multiple applications can be configured to trust each others tokens.
Related
- py-oidc-auth-client — typed Python client for authenticating against services that expose py-oidc-auth-compatible routes.
Development
Development runs through just and containers (Docker or Podman); you do not need Python installed locally:
just dev litestar # Keycloak plus a litestar test app on http://localhost:7777
just test # the test suite, in a container
PY=3.11 just test # on another Python version
just check # lint, types and tests
Run just for all recipes.
Contributing
See the CONTRIBUTING.md document to get involved.
Metadata
Release files for py-oidc-auth 2612.0.0
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 |
|---|---|---|---|---|
| py_oidc_auth-2612.0.0.tar.gz | 56.9 kB | Without provenance | Details for py_oidc_auth-2612.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| py_oidc_auth-2612.0.0-py3-none-any.whl | Python 3 | none | any | Details for py_oidc_auth-2612.0.0-py3-none-any.whl |
Total release size: 123.2 kB
Release files / py_oidc_auth-2612.0.0.tar.gz
| Download URL | py_oidc_auth-2612.0.0.tar.gz |
|---|---|
| Size | 56.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
f47a629d838f6069cb042ab9d77f909a2f9011118273543a7b319cafa1a20c4b
|
|
BLAKE2b-256 checksum How to use checksums |
36f5eda12c1f5b83ef53ccc8c0f90bd9f00821b232515e0f4896a2c2bf9a6e2f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Release files / py_oidc_auth-2612.0.0-py3-none-any.whl
| Download URL | py_oidc_auth-2612.0.0-py3-none-any.whl |
|---|---|
| Size | 66.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
36be8e7e7e82d3d8b2b282199ee0185396efab8423750f0efb2b7f59df49c44e
|
|
BLAKE2b-256 checksum How to use checksums |
b6ef02961de02550d54edf3dc3a26da2632b1ad73ea51937a463fbb0647fce46
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Security for py-oidc-auth 2612.0.0
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.