Step-by-Step Guide to Integrate Active Directory with Django

Satya yellachari goli
2 min readJan 22, 2024

--

Django supports integrating with Active Directory (AD) for authentication through the use of the `django-auth-ldap` library, which is a third-party package that provides LDAP (Lightweight Directory Access Protocol) authentication for Django applications.

Here are the general steps to set up Active Directory authentication in a Django project:

1. Install `django-auth-ldap`:

pip install django-auth-ldap

2. Configure Django Settings:

In your Django project’s settings (usually `settings.py`), configure the LDAP authentication settings.

Below is a minimal example of settings:

AUTHENTICATION_BACKENDS = [
'django_auth_ldap.backend.LDAPBackend',
'django.contrib.auth.backends.ModelBackend', # This is required for fallback
]
# LDAP Server Settings
AUTH_LDAP_SERVER_URI = "ldap://your-ldap-server-url"
AUTH_LDAP_BIND_DN = "CN=your-ldap-bind-user,OU=Users,DC=your-domain,DC=com"
AUTH_LDAP_BIND_PASSWORD = "your-ldap-bind-password"
# Map LDAP attributes to Django user fields
AUTH_LDAP_USER_ATTR_MAP = {
"username": "sAMAccountName",
"first_name": "givenName",
"last_name": "sn",
"email": "mail",
}

Replace the placeholders (`your-ldap-server-url`, `your-ldap-bind-user`, `your-ldap-bind-password`, etc.) with your actual AD server details.

3. LDAP User Search Settings:

Configure settings for searching LDAP for user authentication.

AUTH_LDAP_USER_SEARCH = LDAPSearch(
"OU=Users,DC=your-domain,DC=com", # LDAP search base
ldap.SCOPE_SUBTREE, # Scope
"(sAMAccountName=%(user)s)", # LDAP search filter
)

4. LDAP Group Settings (Optional):

If you want to map LDAP groups to Django permissions, configure group settings.

Adjust these settings to fit your LDAP group structure:

AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_MIRROR_GROUPS = True
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
"OU=Groups,DC=your-domain,DC=com", # LDAP search base for groups
ldap.SCOPE_SUBTREE,
"(objectClass=group)",
)

5. Django Admin Configuration (Optional):

If you want to manage LDAP users and groups from the Django admin interface, you can use the `django-auth-ldap` admin integration.

Add it to your `admin.py`:

from django_auth_ldap.backend import LDAPBackend

admin.site.register(LDAPBackend)

6. Test Authentication:

Finally, test the AD authentication by attempting to log in with a user account from your AD domain.
This is a basic setup for integrating Active Directory authentication with Django.

Please note that the configuration details may vary depending on your AD setup and requirements.

If you have any further doubts please refer to the `django-auth-ldap`:

By following these steps, you should be able to successfully integrate Active Directory authentication with your Django application.

Happy coding!

--

--