Django Quickstart
Integrate UniAuth with Django using mozilla-django-oidc — a third-party OIDC client used after this source example loads advertised metadata and fills explicit settings. Test the exact version, claims, flows, and best-effort logout behavior.
Discovery-first: This source example reads advertised metadata from https://uniauth.id/.well-known/openid-configuration. Configure and test the exact client; the document does not prove every endpoint, claim, or flow.
1. Install
pip install mozilla-django-oidc cryptography2. Environment
# .env
UNIAUTH_CLIENT_ID=uni_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
UNIAUTH_CLIENT_SECRET=unis_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx3. settings.py
# settings.py
import os
INSTALLED_APPS = [
# ...
'mozilla_django_oidc',
'myapp',
]
AUTHENTICATION_BACKENDS = [
'myapp.auth.UniAuthBackend', # custom — see step 5
'django.contrib.auth.backends.ModelBackend',
]
MIDDLEWARE = [
# ...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'mozilla_django_oidc.middleware.SessionRefresh',
]
# ── UniAuth configuration ─────────────────────────────────────────
OIDC_RP_CLIENT_ID = os.environ['UNIAUTH_CLIENT_ID']
OIDC_RP_CLIENT_SECRET = os.environ['UNIAUTH_CLIENT_SECRET']
OIDC_RP_SIGN_ALGO = 'RS256'
# Read the endpoints currently advertised by discovery at startup.
# Validate the exact metadata; later changes can require client updates.
import requests
_disc = requests.get(
'https://uniauth.id/.well-known/openid-configuration',
timeout=5,
).json()
OIDC_OP_AUTHORIZATION_ENDPOINT = _disc['authorization_endpoint']
OIDC_OP_TOKEN_ENDPOINT = _disc['token_endpoint']
OIDC_OP_USER_ENDPOINT = _disc['userinfo_endpoint']
OIDC_OP_JWKS_ENDPOINT = _disc['jwks_uri']
OIDC_OP_LOGOUT_ENDPOINT = _disc['end_session_endpoint']
# Scopes — 'groups' lets you use the OIDC groups claim for RBAC
OIDC_RP_SCOPES = 'openid profile email groups'
# Enable S256 PKCE for this example; verify the effective client policy
OIDC_USE_PKCE = True
# Verify ID token locally (don't roundtrip to /userinfo unless needed)
OIDC_VERIFY_JWT = True
OIDC_CREATE_USER = True
LOGIN_URL = '/oidc/authenticate/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'Alternative (hardcoded endpoints): if startup-time HTTP is a problem for your deployment (e.g. air-gapped), you can hardcode the endpoints instead. Discovery-first is still preferred — it means rollouts that change an endpoint (rare, but possible) don't require a release from your side.
# settings.py — alternative: hardcoded
OIDC_OP_AUTHORIZATION_ENDPOINT = 'https://uniauth.id/api/oauth/authorize'
OIDC_OP_TOKEN_ENDPOINT = 'https://uniauth.id/api/oauth/token'
OIDC_OP_USER_ENDPOINT = 'https://uniauth.id/api/oauth/userinfo'
OIDC_OP_JWKS_ENDPOINT = 'https://uniauth.id/.well-known/jwks.json'
OIDC_OP_LOGOUT_ENDPOINT = 'https://uniauth.id/api/oauth/end-session'4. urls.py
# urls.py
from django.urls import include, path
from myapp.views import backchannel_logout
urlpatterns = [
path('oidc/', include('mozilla_django_oidc.urls')),
path('logout-webhook/', backchannel_logout, name='backchannel_logout'),
# ...
]5. Custom Backend — Map groups Claim to is_staff
# myapp/auth.py
from mozilla_django_oidc.auth import OIDCAuthenticationBackend
class UniAuthBackend(OIDCAuthenticationBackend):
def verify_claims(self, claims):
# Require email_verified before login (no env-var allowlist)
if not claims.get('email_verified'):
return False
return super().verify_claims(claims)
def create_user(self, claims):
user = super().create_user(claims)
self._apply_groups(user, claims)
return user
def update_user(self, user, claims):
user = super().update_user(user, claims)
self._apply_groups(user, claims)
return user
def _apply_groups(self, user, claims):
groups = claims.get('groups', []) or []
# Map UniAuth groups claim to Django staff/superuser
user.is_staff = 'admin' in groups or 'staff' in groups
user.is_superuser = 'admin' in groups
# Set custom attribute if you have one
# user.uniauth_sub = claims['sub']
user.save()6. Back-channel Logout
# myapp/views.py
import requests
from functools import lru_cache
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.conf import settings
from jose import jwt
@lru_cache(maxsize=1)
def _jwks():
return requests.get('https://uniauth.id/.well-known/jwks.json', timeout=5).json()
@csrf_exempt
@require_POST
def backchannel_logout(request):
token = request.POST.get('logout_token', '')
try:
header = jwt.get_unverified_header(token)
claims = jwt.decode(
token, _jwks(),
algorithms=['RS256'],
issuer='https://uniauth.id',
audience=settings.OIDC_RP_CLIENT_ID,
)
except Exception:
return HttpResponse(status=400)
if header.get('typ') != 'logout+jwt':
return HttpResponse(status=400)
if type(claims.get('iat')) is not int or type(claims.get('exp')) is not int:
return HttpResponse(status=400)
if not isinstance(claims.get('jti'), str) or not claims['jti'].strip():
return HttpResponse(status=400)
sub = claims.get('sub') if isinstance(claims.get('sub'), str) and claims['sub'].strip() else None
sid = claims.get('sid') if isinstance(claims.get('sid'), str) and claims['sid'].strip() else None
if not sub and not sid:
return HttpResponse(status=400)
events = claims.get('events')
event = events.get('http://schemas.openid.net/event/backchannel-logout') if isinstance(events, dict) else None
if not isinstance(event, dict):
return HttpResponse(status=400)
if 'nonce' in claims:
return HttpResponse(status=400)
# Your session index should accept the pairwise subject or issued sid.
invalidate_sessions(sub=sub, sid=sid)
return HttpResponse(status=200)Back-channel logout is a Limited Beta requiring operator-managed enrollment. Its URI must use credential-free, fragment-free HTTPS, and the effective ID-token signing algorithm must be RS256.
7. Protecting Views
from django.contrib.auth.decorators import login_required, user_passes_test
@login_required
def dashboard(request):
return render(request, 'dashboard.html')
@user_passes_test(lambda u: u.is_staff)
def admin_panel(request):
return render(request, 'admin.html')