Django API#
Django integration for py-oidc-auth.
Requires Django 4.1+ async views and an ASGI server (e.g. uvicorn, daphne, hypercorn).
Requires the django extra:
pip install py-oidc-auth[django]
conda install -c conda-forge py-oidc-auth-django
Usage:
# views.py
from django.http import JsonResponse
from py_oidc_auth.django_auth import DjangoOIDCAuth
auth = DjangoOIDCAuth(
client_id="my-client",
discovery_url="https://kc.example.com/realms/myrealm/.well-known/openid-configuration",
scopes="myscope profile email",
)
@auth.required()
async def protected(request, token):
return JsonResponse({"sub": token.sub})
# urls.py
from django.urls import path, include
urlpatterns = [
path("api/myapp/", include(auth.get_urlpatterns())),
path("protected", protected),
]
- class py_oidc_auth.django_auth.DjangoOIDCAuth(client_id: str = '', discovery_url: str = '', client_secret: str | None = None, scopes: str = 'profile email', audience: str | None = None, proxy: str = '', claims: Dict[str, Any] | None = None, offline_access: bool = True, timeout_sec: int = 10, jwks_uri: str | None = None, issuer: str | None = None)#
Reusable OIDC authentication wrapper for Django async views.
Use
required()/optional()as view decorators.Call
get_urlpatterns()for a list of Django URL patterns with the standard OIDC endpoints.
- required(claims: Dict[str, Any] | None = None, scopes: str = '') Callable[[F], F]#
Enforce authentication on a Django async view.
The decorated view receives the validated
IDTokenas an extra argument afterrequest:@auth.required() async def protected(request, token): return JsonResponse({"sub": token.sub})
- optional(claims: Dict[str, Any] | None = None, scopes: str = '') Callable[[F], F]#
Allow anonymous access.
The view receives
IDToken | Noneas an extra argument.
- get_urlpatterns(login: str = 'auth/v2/login', callback: str = 'auth/v2/callback', token: str = 'auth/v2/token', device_flow: str | None = 'auth/v2/device', logout: str | None = 'auth/v2/logout', userinfo: str | None = 'auth/v2/userinfo') List[django.urls.URLPattern]#
Return a list of Django URL patterns for standard OIDC routes.
Usage:
from django.urls import path, include urlpatterns = [ path("api/myapp/", include(auth.get_urlpatterns())), ]
Note: route paths should not have a leading slash — Django convention uses relative paths inside
include().