Active Directory authentication in Django

In this article I showed you how to authenticate users of your Django apps against a LDAP server. It's quite easy with open-sourced software huh?! But, if your current infrastructure is built on a proprietary software like MS Active Directory, you will need an extra effort to plug in your Django projects. I will show you how. Read on!

Here are the important settings for django-auth-ldap module you need to set:

* USER SEARCH:

AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=All Users,DC=MYAD,DC=COM", ldap.SCOPE_SUBTREE, '(SAMAccountName=%(user)s)')


* GROUP SEARCH:

# Set up the basic group parameters.
AUTH_LDAP_GROUP_SEARCH = LDAPSearch("OU=User Groups,OU=All Users,DC=MYAD,DC=COM", \
                    ldap.SCOPE_SUBTREE, "(objectClass=organizationalUnit)"),

#!important! set group type
AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType()


* USER FLAGS:

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    "is_active": ["CN=Administrators,OU=User Groups,OU=All Users,DC=MYAD,DC=COM", 
                "CN=Editors,OU=User Groups,OU=All Users,DC=MYAD,DC=COM",
                "CN=Readers,OU=User Groups,OU=All Users,DC=MYAD,DC=COM"],
    "is_staff": "CN=Editors,OU=All Users,DC=MYAD,DC=COM",
    "is_superuser": "CN=Administrators,OU=All Users,DC=MYAD,DC=COM",
}

* GROUP MIRROR:

# important! to match the group's permission
AUTH_LDAP_MIRROR_GROUPS = True

* Important! AUTHENTICATION_BACKENDS:

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

And, it is really useful to turn on logging for django-auth-ldap:

import logging

logger = logging.getLogger('django_auth_ldap')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

(To see logs in console and in django-debug-toolbar)


Here is the complete working settings:


Comments