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]

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",
)

@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 = 'openid profile email', proxy: str = '', claims: Dict[str, Any] | None = None, timeout_sec: int = 10)#

Reusable OIDC authentication wrapper for Django async views.

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 IDToken as an extra argument after request:

@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 | None as 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().