This article describes how to use Django-auth-ldap in detail, the meanings of parameters, and provides example codes

Release notes

  • Django = = 2.2
  • Django – auth – ldap = = 1.7.0

The integration process

There is a django-Auth-LDAP module available for Django integration with LDAP authentication, and this article will focus on using this module first

pip install django-auth-ldap
Copy the code

Then add the following content to the setting. Py global configuration file to work normally:

import ldap
from django_auth_ldap.config import LDAPSearch, GroupOfNamesType

# Baseline configuration.
AUTH_LDAP_SERVER_URI = 'ldap://ldap.ops-coffee.cn'

AUTH_LDAP_BIND_DN = 'uid=authz,ou=Public,dc=ops-coffee,dc=cn'
AUTH_LDAP_BIND_PASSWORD = 'CzfdX629K7'

AUTH_LDAP_USER_SEARCH = LDAPSearch(
    'ou=People,dc=ops-coffee,dc=cn',
    ldap.SCOPE_SUBTREE,
    '(uid=%(user)s)'.)# Or:
# AUTH_LDAP_USER_DN_TEMPLATE = 'uid=%(user)s,ou=People,dc=ops-coffee,dc=cn'

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

AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend'.'django.contrib.auth.backends.ModelBackend'.)Copy the code

The preceding configuration is explained in detail:

AUTH_LDAP_SERVER_URI: indicates the IP address of the LDAP server

AUTH_LDAP_BIND_DN: a complete user DN used to log in to the LDAP server and verify that the entered account and password are correct

AUTH_LDAP_BIND_PASSWORD: indicates the password of user BIND_DN. Here we briefly explain LDAP authentication logic to better understand why these two configurations are required

Django uses AUTH_LDAP_BIND_DN and AUTH_LDAP_BIND_PASSWORD as the username and password to log in to the LDAP server. If the number of items searched is 0 or greater than 1, an error is returned. If the number of items searched is equal to 1, the DN of the item searched is used to match the password entered by the user. If the login succeeds, the system returns the login permission; if the login fails, the system does not allow the login

AUTH_LDAP_USER_SEARCH: indicates the range of users that can log in through LDAP. If the preceding configuration is configured, ou=People,dc=ops-coffee,dc=cn are used to search for users

(uid=%(user)s)’ specifies the LDAP attribute that corresponds to Django username

The preceding configuration is used to search for users in one OU. If you need to search for users in multiple OU, perform the following configuration:

from django_auth_ldap.config import LDAPSearch, LDAPSearchUnion

AUTH_LDAP_USER_SEARCH = LDAPSearchUnion(
    LDAPSearch(
        'ou=Public,dc=ops-coffee,dc=cn',
        ldap.SCOPE_SUBTREE,
        '(uid=%(user)s)'
    ),
    LDAPSearch(
        'ou=PeoPle,dc=ops-coffee,dc=cn',
        ldap.SCOPE_SUBTREE,
        '(uid=%(user)s)'),Copy the code

AUTH_LDAP_USER_ATTR_MAP: Specifies the mapping between LDAP User attributes and Django User attributes. After a User logs in to Django for the first time and succeeds in authentication, the LDAP User attributes are written to the Django User table

AUTHENTICATION_BACKENDS: Configures djangos backend authentication list

When Django calls the Auth. authenticate method for authentication, Django will try all the authentication backends specified in the AUTHENTICATION_BACKENDS tuple. If the first authentication method fails, Django will continue to try the next one until all authentication methods have been attempted

Django is the default authentication backend Django. Contrib. Auth. Backends. ModelBackend, as above configuration we add the ldap authentication to the AUTHENTICATION_BACKENDS, If the User fails, Django will query the User table in the local database to verify the User. If you only want Django to authenticate LDAP and not the local database, remove the ModelBackend configuration in AUTHENTICATION_BACKENDS

Other django-auth-ldap global configuration parameters are explained as follows:

AUTH_LDAP_ALWAYS_UPDATE_USER: specifies whether to synchronize LDAP changes. The default value is True, that is, the LDAP User is automatically updated to the Django User table when the User passes LDAP authentication. If the value is False, the User is not automatically updated

AUTH_LDAP_CACHE_TIMEOUT: set the LDAP authentication cache time

Login authentication

If the preceding configurations are correct, you can log in to the LDAP system using an LDAP account. The default login logic and front-end login code do not need to be modified

If you encounter problems in the debugging process, I prepared a demo source code for reference, public number background reply 09 to obtain the address

Advanced configuration

Django-auth-ldap advanced configuration is mainly used to explain the configuration of groups in Django-auth-LDAP. This requires some concept of LDAP groups. To facilitate understanding, we will use practical examples to illustrate the configuration

Suppose we have three groups: Overmind, Kerrigan and Admin. The configuration is as follows:

# ldapsearch -LLL -x -D "uid=authz,ou=Public,dc=ops-coffee,dc=cn" -w "CzfdX629K7" -b cn=overmind,ou=Group,dc=ops-coffee,dc=cn 
dn: cn=overmind,ou=Group,dc=ops-coffee,dc=cn
cn: overmind
member: uid=sre,ou=People,dc=ops-coffee,dc=cn
objectClass: groupOfNames
objectClass: top
Copy the code
# ldapsearch -LLL -x -D "uid=authz,ou=Public,dc=ops-coffee,dc=cn" -w "CzfdX629K7" -b cn=kerrigan,ou=Group,dc=ops-coffee,dc=cn 
dn: cn=kerrigan,ou=Group,dc=ops-coffee,dc=cn
cn: kerrigan
objectClass: groupOfNames
objectClass: top
member: uid=u1,ou=Public,dc=ops-coffee,dc=cn
member: uid=u2,ou=People,dc=ops-coffee,dc=cn
Copy the code
# ldapsearch -LLL -x -D "uid=authz,ou=Public,dc=ops-coffee,dc=cn" -w "CzfdX629K7" -b cn=admin,ou=Group,dc=ops-coffee,dc=cn 
dn: cn=admin,ou=Group,dc=ops-coffee,dc=cn
cn: admin
member: uid=u3,ou=Admin,dc=ops-coffee,dc=cn
objectClass: groupOfNames
objectClass: top
Copy the code

We need to implement Django integrated LDAP authentication, and do not allow users belonging to the Kerrigan group to log in to the system. If users belong to the Admin group, they need to log in to Django as administrators. The following configuration explains how to implement this requirement

Django-auth-ldap group configuration:

AUTH_LDAP_GROUP_SEARCH = LDAPSearch(
    'ou=Group,dc=ops-coffee,dc=cn',
    ldap.SCOPE_SUBTREE,
    '(objectClass=groupOfNames)',
)
AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr='cn')

# Simple group restrictions
# AUTH_LDAP_REQUIRE_GROUP = 'cn=overmind,ou=Group,dc=ops-coffee,dc=cn'
AUTH_LDAP_DENY_GROUP = 'cn=kerrigan,ou=Group,dc=ops-coffee,dc=cn'

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    'is_superuser': 'cn=admin,ou=Group,dc=ops-coffee,dc=cn',}Copy the code

The configuration is explained as follows:

AUTH_LDAP_GROUP_SEARCH: searches for information under an OU. This parameter is similar to the AUTH_LDAP_USER_SEARCH parameter. Ou refers to the group directory, for example, ou= group,dc=ops-coffee,dc=cn

AUTH_LDAP_GROUP_TYPE: indicates the returned Group type and the first attribute value of Group DN. For example, Group DNcn=overmind,ou=Group,dc=ops-coffee,dc=cn

AUTH_LDAP_REQUIRE_GROUP: Sets which group members are allowed to log in. This can be set if only members of the Overmind group are allowed to log in

AUTH_LDAP_REQUIRE_GROUP = 'cn=overmind,ou=Group,dc=ops-coffee,dc=cn'
Copy the code

AUTH_LDAP_DENY_GROUP: Set which group members are denied login. This can be set if we do not allow kerrigan group members to login

AUTH_LDAP_DENY_GROUP = 'cn=kerrigan,ou=Group,dc=ops-coffee,dc=cn'
Copy the code

When the user belongs to overmind group and Kerrigan group at the same time, that is, the user is both allowed to log in and refused to log in, then the user cannot log in based on the refused login

AUTH_LDAP_USER_FLAGS_BY_GROUP: Set additional Django user properties based on the LDAP group. For example, if we want to set the LDAP admin group to have Django super administrator privileges, in addition to manually setting this in Django, You can also set AUTH_LDAP_USER_FLAGS_BY_GROUP directly in the Setting

AUTH_LDAP_USER_FLAGS_BY_GROUP = {
    'is_superuser': 'cn=admin,ou=Group,dc=ops-coffee,dc=cn',}Copy the code

The is_superuser attribute is automatically set to True when the admin group user logs in

At this point, we have a comprehensive understanding of Django-Auth-LDAP, which can be easily integrated into the actual project. If you have any questions, please refer to my Github code

Record on pit

Django-auth-ldap: django-auth-ldap: django-auth-ldap

c:\users\ops-coffee\appdata\local\temp\pip-install-sec1o036\python-ldap\modules\constants.h(7): fatal error C1083: Cannot open include file: 'lber.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
Copy the code

This error requires manual installation of WHL file as follows:

Start at www.lfd.uci.edu/~gohlke/pyt… Download the python-LDAP WHL file of the corresponding version

Then use the PIP command to install WHL, making sure the file path is correct

D:\demo\openldap>python -m PIP install python_ldap-3.2.0-cp36-cp36m-win_amd64. WHL Processing D :\demo\openldap\ python_ldAP-3.2.0-cp36-cp36m-win_amd64. WHL Requirement already SATISFIED: pyASn1 >=0.3.7inC: python36\lib\site-packages (from python-ldap==3.2.0) (0.4.2) Requirement already satisfied: pyasn1-modules>=0.1.5inC :\python36\lib\site-packages (from python-ldap==3.2.0) (0.2.4) Installing COLLECTED packages: Python - ldap Successfully installed python - ldap - 3.2.0Copy the code

Related articles recommended reading:

  • Deploy and manage OpenLDAP
  • Django+JWT implements Token authentication