Read our how to authenticate users to the University Access Management platform (Azure AD) using OpenID Connect web page before following these instructions.
If you’re writing a Python Django application you can use a Django plugin which allows you to use Azure AD as the authentication source for Django’s native authentication & authorization services. Read the ADFS Authentication for Django documentation.
-
Add the django-auth-adfs module to your application.
$ pip install django-auth-adfs
Don’t forget to update your requirements.txt file!
-
Edit the settings.py file for your application.
Add the following list:
AUTHENTICATION_BACKENDS = [ 'django_auth_adfs.backend.AdfsAuthCodeBackend', 'django_auth_adfs.backend.AdfsAccessTokenBackend', ]
-
At the start of the INSTALLED_APPS list, add django_auth_adfs
INSTALLED_APPS = [ ... 'django_auth_adfs', 'django.contrib.auth', ]
-
At the end of the MIDDLEWARE list, add django_auth_adfs.middleware.LoginRequiredMiddleware
MIDDLEWARE = [
...
'django_auth_adfs.middleware.LoginRequiredMiddleware',
]This middleware ensures all access to your application is authenticated by Azure AD.
-
Finally, at the end of settings.py add the following pieces:
AUTH_ADFS = { 'AUDIENCE': 'YOUR APPLICATION CLIENT ID', 'CLIENT_ID': 'YOUR APPLICATION CLIENT ID', 'CLIENT_SECRET': 'YOUR APPLICATION CLIENT SECRET', 'CLAIM_MAPPING': {'first_name': 'given_name', 'last_name': 'family_name', 'email': 'upn'}, 'GROUPS_CLAIM': None, 'MIRROR_GROUPS': False, 'USERNAME_CLAIM': 'upn', 'TENANT_ID': '49a50445-bdfa-4b79-ade3-547b4f3986e9', 'RELYING_PARTY_ID': 'YOUR APPLICATION CLIENT ID', 'VERSION': 'v1.0', 'LOGIN_EXEMPT_URLS': [ '^S', ], } # Configure django to redirect users to the right URL for login LOGIN_URL = "django_auth_adfs:login" LOGIN_REDIRECT_URL = "/"
If you do not want all access to your application protected by Azure AD you can edit the LOGIN_EXEMPT_URLS list in the AUTH_ADFS dictionary to indicate which URLs to exclude.
AUTH_ADFS = { … "LOGIN_EXEMPT_URLS": ["api/", "public/"], … }
When a user authenticates to your application, an entry is made in the standard Django auth_user table:
# SELECT username, last_login FROM auth_user;
username
last_login
fjc55@cam.ac.uk
2023-07-13 13:41:18.91661+01