Django LDAP Authentication Backend

5.3.0 · active · verified Tue Apr 14

django-auth-ldap is a Django authentication backend that integrates with LDAP (Lightweight Directory Access Protocol) services, allowing Django applications to authenticate users against an LDAP server. It provides rich configuration options for managing users, groups, and permissions. Currently at version 5.3.0, the library is actively maintained with frequent releases to support the latest Django and Python versions.

Warnings

Install

Imports

Quickstart

This quickstart configures `django-auth-ldap` to authenticate users against an LDAP server, synchronize user attributes, and mirror LDAP groups to Django. It assumes basic LDAP setup and uses environment variables for sensitive data. Remember to adjust search bases and attribute mappings to match your LDAP directory structure. Ensure `python-ldap`'s system dependencies are installed for successful installation.

import os
import ldap
from django_auth_ldap.config import LDAPSearch, LDAPGroupQuery

AUTHENTICATION_BACKENDS = [
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
]

AUTH_LDAP_SERVER_URI = os.environ.get('AUTH_LDAP_SERVER_URI', 'ldap://localhost:389')
AUTH_LDAP_BIND_DN = os.environ.get('AUTH_LDAP_BIND_DN', '')
AUTH_LDAP_BIND_PASSWORD = os.environ.get('AUTH_LDAP_BIND_PASSWORD', '')

AUTH_LDAP_USER_SEARCH = LDAPSearch(
    os.environ.get('AUTH_LDAP_USER_SEARCH_BASE', 'ou=users,dc=example,dc=com'),
    ldap.SCOPE_SUBTREE,
    "uid=%(user)s"
)

AUTH_LDAP_USER_ATTR_MAP = {
    'first_name': 'givenName',
    'last_name': 'sn',
    'email': 'mail'
}

AUTH_LDAP_MIRROR_GROUPS = True
AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
    os.environ.get('AUTH_LDAP_GROUP_SEARCH_BASE', 'ou=groups,dc=example,dc=com'),
    ldap.SCOPE_SUBTREE,
    '(objectClass=groupOfNames)'
)
AUTH_LDAP_GROUP_TYPE = LDAPGroupQuery()

# Populate Group permissions
AUTH_LDAP_FIND_GROUP_PERMS = True
AUTH_LDAP_CACHE_TIMEOUT = 3600 # Cache for 1 hour

# Optional: Require valid TLS certificate from LDAP server
AUTH_LDAP_START_TLS = True
# AUTH_LDAP_GLOBAL_OPTIONS = {
#     ldap.OPT_X_TLS_CACERTFILE: os.environ.get('LDAP_TLS_CACERTFILE', '/path/to/ca.pem'),
#     ldap.OPT_X_TLS_CERTFILE: os.environ.get('LDAP_TLS_CERTFILE', '/path/to/client.pem'),
#     ldap.OPT_X_TLS_KEYFILE: os.environ.get('LDAP_TLS_KEYFILE', '/path/to/client.key')
# }

view raw JSON →