Django and LDAP

LDAP GraphicA project at work requires that I authenticate users using an LDAP service. Who knew it would be so easy?!?

I’m using Django 1.9.2, but I imagine that this will work with other versions +/- a few releases. Python version is 3.5.

INSTALL

The library that does the magic is django-auth-ldap. For Python 3.x, pyldap is required, while python-ldap is used for Python 2.x. I also had to install some system libraries: libsasl2-dev, python-dev, libldap2-dev, and libssl-dev (on Ubuntu).

AUTHENTICATION_BACKENDS

The AUTHENTICATION_BACKENDS setting is not defined in the default Django settings.py file using v1.9.2. However, the code I use below expects the variable to exist. Therefore, I added it in with the default setting. You may have other backends already in use.

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

LDAP SETTINGS

This code lives at the end of settings.py. Use your own LDAP URI, ou (Organizational Unit), and dc (Domain Component).

#-----------------------------------------------------------------------------#
#
#   LDAP Settings
#
#-----------------------------------------------------------------------------#

AUTHENTICATION_BACKENDS += ('django_auth_ldap.backend.LDAPBackend',) 

AUTH_LDAP_SERVER_URI = "ldaps://your.ldap.server"

AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

The first line adds an additional authentication backend to the tuple. Next, we define the path to the server. Note that I’ve used a secure protocol (ldaps). This is essential to keep the credentials passed to the server encrypted. The third line sets up a direct bind with the supplied user.

In place of the direct bind method, the documentation also suggests a user search configuration. I was able to get this to work as well, but it requires that your password be included in settings.py (or you are performing some trickery to get the password). My LDAP admin is not fond of this method, but will create an application-only account if needed. Here is the user search configuration:

import ldap
from django_auth_ldap.config import LDAPSearch

AUTH_LDAP_BIND_DN = "<user>"
AUTH_LDAP_BIND_PASSWORD = "<password>"
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
    ldap.SCOPE_SUBTREE, "(uid=%(user)s)")

I’m sorry to say that I’m not an LDAP expert at all, so I can’t supply much advice if this doesn’t work for you. Buy your LDAP admin a lunch sometime and ask your questions while waiting for the food.

Best of luck!!