Skip to content

Configure Django-based web applications to use Entra ID sign in

In this guide we will cover the minimal steps to add Entra ID sign in to your Django applications.

Prerequisites

Register a sign in application with the Entra ID Application Factory as described in the dedicated how to guide. We will re-use the "Punt Booker" example from that guide. When using Django, the redirect URL path should be /accounts/complete/azuread-tenant-oauth2/ and we can use the default JSON template.

So, for the production application, the application configuration is as follows. Lines which are different to the example in that how to guide have been highlighted.

applications/production/punt-booker-production.yaml
type: sign-in

display_name: Punt Booker
logo_image: punt-booker.png

web_redirect_uris:
  - https://punt-booker.apps.cam.ac.uk/accounts/complete/azuread-tenant-oauth2/

credential_secrets:
  sign_in:
    template: default
    iam_policy:
      "roles/secretmanager.secretAccessor":
        - webapp@punt-booker-prod.iam.gserviceaccount.com

Ensure that the secret containing application credentials is mounted inside the container at /secrets/entra-id/credentials.json.

Configure Django

Add python-social-auth as a dependency of your application.

Add the following to settings.py.

settings.py
import json

# ... later on ...

with open("/secrets/entra-id/credentials.json") as f:
    _entra_id_credentials = json.load(f)

SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_TENANT_ID = _entra_id_credentials["tenant_id"]
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_KEY = _entra_id_credentials["client_id"]
SOCIAL_AUTH_AZUREAD_TENANT_OAUTH2_SECRET = _entra_id_credentials["client_secret"]

Add social_core.backends.azuread_tenant.AzureADTenantOAuth2 to AUTHENTICATION_BACKENDS.

Set LOGIN_URL to /accounts/login/azuread-tenant-oauth2/.

Perform any additional configuration as indicated in the python-social-auth documentation.

Use the user's email address as their username

By default python-social-auth generates a random username for a user. You may want to make the user's email address their username. This can be done by:

  • Adding SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = True to settings.py.
  • Adding social_core.pipeline.social_auth.associate_by_email to SOCIAL_AUTH_PIPELINE above social_core.pipeline.user.create_user.

Summary

In this guide we covered minimal steps to add Entra ID authentication to Django applications.

Next steps