Django: logowanie przez OpenID Connect z mozilla-django-oidc

Potrzebujesz trzech wartości z konsoli dla deweloperów: identyfikatora klienta, sekretu klienta (tylko aplikacje serwerowe) i zarejestrowanego URI przekierowania. Resztę zawiera dokument discovery pod adresem https://identity.dazr.eu/.well-known/openid-configuration.

Django

Użyj mozilla-django-oidc. Zarejestruj aplikację serwerową z URI przekierowania https://app.example.eu/oidc/callback/. Biblioteka nie czyta dokumentu discovery, dlatego endpointy są wpisane wprost.

# settings.py
import os

INSTALLED_APPS += ["mozilla_django_oidc"]  # after django.contrib.auth
AUTHENTICATION_BACKENDS = [
    "mozilla_django_oidc.auth.OIDCAuthenticationBackend",
    "django.contrib.auth.backends.ModelBackend",
]

OIDC_RP_CLIENT_ID = os.environ["DAZR_CLIENT_ID"]
OIDC_RP_CLIENT_SECRET = os.environ["DAZR_CLIENT_SECRET"]
OIDC_RP_SCOPES = "openid profile email"
OIDC_RP_SIGN_ALGO = "ES256"
OIDC_OP_JWKS_ENDPOINT = "https://identity.dazr.eu/oauth/jwks"
OIDC_OP_AUTHORIZATION_ENDPOINT = "https://identity.dazr.eu/oauth/authorize"
OIDC_OP_TOKEN_ENDPOINT = "https://identity.dazr.eu/oauth/token"
OIDC_OP_USER_ENDPOINT = "https://identity.dazr.eu/oauth/userinfo"
OIDC_USE_PKCE = True
OIDC_PKCE_CODE_CHALLENGE_METHOD = "S256"

LOGIN_REDIRECT_URL = "/"
LOGOUT_REDIRECT_URL = "/"

# urls.py
from django.urls import include, path
urlpatterns += [path("oidc/", include("mozilla_django_oidc.urls"))]

# template: start the sign-in
# <a href="{% url 'oidc_authentication_init' %}">Sign in with Dazr Identity</a>

Domyślnie backend dopasowuje użytkowników po adresie e-mail. Aby łączyć konta przez sub, utwórz podklasę OIDCAuthenticationBackend i nadpisz filter_users_by_claims oraz create_user. Używaj aktualnej wersji: starsze wersje nie weryfikują podpisów ES256.

Więcej dla deweloperów