LDAP Authentication

LDAP Authentication has two binding options, depending on your business case. We recommend using the Search/Bind method over the Direct Bind method.LDAP Authentication has two binding options, depending on your business case. We recommend using the Search/Bind method over the Direct Bind method.

Search/Bind Approach

We recommend using the Search/Bind method. You must connect to the LDAP server anonymously or with a fixed account, and search for the distinguished name (DN) of the user. After the DN is found, you can attempt a bind with the user's password.

Here is the code for a simple search/bind approach that completes an anonymous bind, searches the OU for an object that matched the UID of the user’s name, and attempts to bind using that DN and the user’s password. The authentication fails unless the search returns exactly one result. If anonymous search is not possible, set AUTH_LDAP_BIND_DN to the DN of an authorized user, and AUTH_LDAP_BIND_PASSWORD to the password.

import ldap
from django_auth_ldap.config import LDAPSearch

AUTH_LDAP_BIND_DN = ""
AUTH_LDAP_BIND_PASSWORD = ""
AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
Direct Bind Approach

In the absence of a Bind user, you should use Direct Bind. It does not perform a search; instead, it checks in a template to directly authenticate the user's DN. The placeholder for the template is %(user)s. This approach has the disadvantage that it may not query groups correctly.

Here is the code for a simple direct bind approach:

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

Optionally,

  • AUTH_LDAP_USER_FLAGS_BY_GROUP sets the user attributes line for first and last name.
  • AUTH_LDAP_USER_ATTR_MAP sets user flags, such as is_superuser, which we use to define an LDAP group for arcviz admins.

For more information, see https://django-auth-ldap.readthedocs.io/en/latest/reference.html.