django-auth-ldap documentation

46
django-auth-ldap Documentation Release 1.5.0 Peter Sagerson Apr 19, 2018

Upload: others

Post on 18-Oct-2021

55 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: django-auth-ldap Documentation

django-auth-ldap DocumentationRelease 1.5.0

Peter Sagerson

Apr 19, 2018

Page 2: django-auth-ldap Documentation
Page 3: django-auth-ldap Documentation

Contents

1 Installation 3

2 Authentication 52.1 Server Config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.2 Search/Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52.3 Direct Bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.4 Customizing Authentication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62.5 Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Working With Groups 93.1 Types of Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93.2 Finding Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.3 Limiting Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

4 User objects 114.1 Populating Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114.2 Easy Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.3 Updating Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.4 Direct Attribute Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

5 Permissions 155.1 Using Groups Directly . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155.2 Group Mirroring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155.3 Non-LDAP Users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

6 Multiple LDAP Configs 17

7 Logging 19

8 Performance 21

9 Example Configuration 23

10 Reference 2510.1 Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2510.2 Module Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.3 Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2910.4 Backend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

i

Page 4: django-auth-ldap Documentation

11 Change Log 3311.1 1.5.0 - 2018-04-18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3311.2 1.4.0 - 2018-03-22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3311.3 1.3.0 - 2017-11-20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3311.4 1.2.16 - 2017-09-30 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.5 1.2.15 - 2017-08-17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.6 1.2.14 - 2017-07-24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.7 1.2.13 - 2017-06-19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.8 1.2.12 - 2017-05-20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.9 1.2.11 - 2017-04-22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.10 1.2.9 - 2017-02-14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3411.11 1.2.8 - 2016-04-18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.12 1.2.7 - 2015-09-29 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.13 1.2.6 - 2015-03-29 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.14 1.2.5 - 2015-01-30 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.15 1.2.4 - 2014-12-28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.16 1.2.3 - 2014-11-18 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.17 1.2.2 - 2014-09-22 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.18 1.2.1 - 2014-08-24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3511.19 1.2 - 2014-04-10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3611.20 1.1.8 - 2014-02-01 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3611.21 1.1.7 - 2013-11-19 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3611.22 1.1.5 - 2013-10-25 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3611.23 1.1.4 - 2013-03-09 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3611.24 1.1.3 - 2013-01-05 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

12 License 37

Python Module Index 39

ii

Page 5: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

This is a Django authentication backend that authenticates against an LDAP service. Configuration can be as simpleas a single distinguished name template, but there are many rich configuration options for working with users, groups,and permissions.

• Repository: https://github.com/django-auth-ldap/django-auth-ldap

• Documentation: https://django-auth-ldap.readthedocs.io/

This version is supported on Python 2.7 and 3.4+; and Django 1.11+. It requires python-ldap >= 3.0.

Contents 1

Page 6: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

2 Contents

Page 7: django-auth-ldap Documentation

CHAPTER 1

Installation

Install the package with pip:

$ pip install django-auth-ldap

It requires python-ldap >= 3.0. You’ll need the OpenLDAP libraries and headers available on your system.

To use the auth backend in a Django project, add 'django_auth_ldap.backend.LDAPBackend' toAUTHENTICATION_BACKENDS. Do not add anything to INSTALLED_APPS.

AUTHENTICATION_BACKENDS = ['django_auth_ldap.backend.LDAPBackend',

]

LDAPBackend should work with custom user models, but it does assume that a database is present.

Note: LDAPBackend does not inherit from ModelBackend. It is possible to use LDAPBackend exclusively byconfiguring it to draw group membership from the LDAP server. However, if you would like to assign permissions toindividual users or add users to groups within Django, you’ll need to have both backends installed:

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

]

3

Page 8: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

4 Chapter 1. Installation

Page 9: django-auth-ldap Documentation

CHAPTER 2

Authentication

2.1 Server Config

If your LDAP server isn’t running locally on the default port, you’ll want to start by settingAUTH_LDAP_SERVER_URI to point to your server. The value of this setting can be anything that your LDAPlibrary supports. For instance, openldap may allow you to give a comma- or space-separated list of URIs to try insequence.

AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"

If your server location is even more dynamic than this, you may provide a function (or any callable object) that returnsthe URI. You should assume that this will be called on every request, so if it’s an expensive operation, some cachingis in order.

from my_module import find_my_ldap_server

AUTH_LDAP_SERVER_URI = find_my_ldap_server

If you need to configure any python-ldap options, you can set AUTH_LDAP_GLOBAL_OPTIONS and/orAUTH_LDAP_CONNECTION_OPTIONS. For example, disabling referrals is not uncommon:

import ldap

AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS: 0

}

2.2 Search/Bind

Now that you can talk to your LDAP server, the next step is to authenticate a username and password. There aretwo ways to do this, called search/bind and direct bind. The first one involves connecting to the LDAP server either

5

Page 10: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

anonymously or with a fixed account and searching for the distinguished name of the authenticating user. Then wecan attempt to bind again with the user’s password. The second method is to derive the user’s DN from his usernameand attempt to bind as the user directly.

Because LDAP searches appear elsewhere in the configuration, the LDAPSearch class is provided to encapsulatesearch information. In this case, the filter parameter should contain the placeholder %(user)s. A simple configura-tion for the search/bind approach looks like this (some defaults included for completeness):

import ldapfrom 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)")

This will perform an anonymous bind, search under "ou=users,dc=example,dc=com" for an object with auid matching the user’s name, and try to bind using that DN and the user’s password. The search must return exactlyone result or authentication will fail. If you can’t search anonymously, you can set AUTH_LDAP_BIND_DN to thedistinguished name of an authorized user and AUTH_LDAP_BIND_PASSWORD to the password.

2.2.1 Search Unions

New in version 1.1.

If you need to search in more than one place for a user, you can use LDAPSearchUnion. This takes multipleLDAPSearch objects and returns the union of the results. The precedence of the underlying searches is unspecified.

import ldapfrom django_auth_ldap.config import LDAPSearch, LDAPSearchUnion

AUTH_LDAP_USER_SEARCH = LDAPSearchUnion(LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)"),LDAPSearch("ou=otherusers,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)

→˓"),)

2.3 Direct Bind

To skip the search phase, set AUTH_LDAP_USER_DN_TEMPLATE to a template that will produce the authenticatinguser’s DN directly. This template should have one placeholder, %(user)s. If the first example had used ldap.SCOPE_ONELEVEL, the following would be a more straightforward (and efficient) equivalent:

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

2.4 Customizing Authentication

New in version 1.3.

It is possible to further customize the authentication process by subclassing LDAPBackend and overridingauthenticate_ldap_user(). The first argument is the unauthenticated ldap_user, the second is the suppliedpassword. The intent is to give subclasses a simple pre- and post-authentication hook.

6 Chapter 2. Authentication

Page 11: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

If a subclass decides to proceed with the authentication, it must call the inherited implementation. It may then returneither the authenticated user or None. The behavior of any other return value–such as substituting a different userobject–is undefined. User objects has more on managing Django user objects.

Obviously, it is always safe to access ldap_user.dn before authenticating the user. Accessingldap_user.attrs and others should be safe unless you’re relying on special binding behavior, such asAUTH_LDAP_BIND_AS_AUTHENTICATING_USER.

2.5 Notes

LDAP is fairly flexible when it comes to matching DNs. LDAPBackend makes an effort to accommodate this byforcing usernames to lower case when creating Django users and trimming whitespace when authenticating.

Some LDAP servers are configured to allow users to bind without a password. As a precaution against false positives,LDAPBackend will summarily reject any authentication attempt with an empty password. You can disable thisbehavior by setting AUTH_LDAP_PERMIT_EMPTY_PASSWORD to True.

By default, all LDAP operations are performed with the AUTH_LDAP_BIND_DN andAUTH_LDAP_BIND_PASSWORD credentials, not with the user’s. Otherwise, the LDAP connection wouldbe bound as the authenticating user during login requests and as the default credentials during other re-quests, so you might see inconsistent LDAP attributes depending on the nature of the Django view. If you’rewilling to accept the inconsistency in order to retrieve attributes while bound as the authenticating user, seeAUTH_LDAP_BIND_AS_AUTHENTICATING_USER.

By default, LDAP connections are unencrypted and make no attempt to protect sensitive information, such as pass-words. When communicating with an LDAP server on localhost or on a local network, this might be fine. If you needa secure connection to the LDAP server, you can either use an ldaps:// URL or enable the StartTLS extension.The latter is generally the preferred mechanism. To enable StartTLS, set AUTH_LDAP_START_TLS to True:

AUTH_LDAP_START_TLS = True

If LDAPBackend receives an LDAPError from python_ldap, it will normally swallow it and log a warning. If you’dlike to perform any special handling for these exceptions, you can add a signal handler to django_auth_ldap.backend.ldap_error. The signal handler can handle the exception any way you like, including re-raising it orany other exception.

2.5. Notes 7

Page 12: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

8 Chapter 2. Authentication

Page 13: django-auth-ldap Documentation

CHAPTER 3

Working With Groups

3.1 Types of Groups

Working with groups in LDAP can be a tricky business, mostly because there are so many different kinds. This moduleincludes an extensible API for working with any kind of group and includes implementations for the most commonones. LDAPGroupType is a base class whose concrete subclasses can determine group membership for particulargrouping mechanisms. Four built-in subclasses cover most grouping mechanisms:

• PosixGroupType

• MemberDNGroupType

• NestedMemberDNGroupType

posixGroup and nisNetgroup objects are somewhat specialized, so they get their own classes. The other two covermechanisms whereby a group object stores a list of its members as distinguished names. This includes groupOfNames,groupOfUniqueNames, and Active Directory groups, among others. The nested variant allows groups to contain othergroups, to as many levels as you like. For convenience and readability, several trivial subclasses of the above areprovided:

• GroupOfNamesType

• NestedGroupOfNamesType

• GroupOfUniqueNamesType

• NestedGroupOfUniqueNamesType

• ActiveDirectoryGroupType

• NestedActiveDirectoryGroupType

• OrganizationalRoleGroupType

• NestedOrganizationalRoleGroupType

9

Page 14: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

3.2 Finding Groups

To get started, you’ll need to provide some basic information about your LDAP groups.AUTH_LDAP_GROUP_SEARCH is an LDAPSearch object that identifies the set of relevant group objects.That is, all groups that users might belong to as well as any others that we might need to know about (in the case ofnested groups, for example). AUTH_LDAP_GROUP_TYPE is an instance of the class corresponding to the type ofgroup that will be returned by AUTH_LDAP_GROUP_SEARCH . All groups referenced elsewhere in the configurationmust be of this type and part of the search results.

import ldapfrom django_auth_ldap.config import LDAPSearch, GroupOfNamesType

AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=example,dc=com",ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"

)AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()

3.3 Limiting Access

The simplest use of groups is to limit the users who are allowed to log in. If AUTH_LDAP_REQUIRE_GROUP is set,then only users who are members of that group will successfully authenticate. AUTH_LDAP_DENY_GROUP is thereverse: if given, members of this group will be rejected.

AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=example,dc=com"AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=groups,dc=example,dc=com"

However, these two settings alone may not be enough to satisfy your needs. In such cases, you can use theLDAPGroupQuery object to perform more complex matches against a user’s groups. For example:

from django_auth_ldap.config import LDAPGroupQuery

AUTH_LDAP_REQUIRE_GROUP = ((

LDAPGroupQuery("cn=enabled,ou=groups,dc=example,dc=com") |LDAPGroupQuery("cn=also_enabled,ou=groups,dc=example,dc=com")

) &~LDAPGroupQuery("cn=disabled,ou=groups,dc=example,dc=com")

)

It is important to note a couple features of the example above. First and foremost, this handles the case of bothAUTH_LDAP_REQUIRE_GROUP and AUTH_LDAP_DENY_GROUP in one setting. Second, you can use three op-erators on these queries: &, |, and ~: and, or, and not, respectively.

When groups are configured, you can always get the list of a user’s groups from user.ldap_user.group_dnsor user.ldap_user.group_names. More advanced uses of groups are covered in the next two sections.

10 Chapter 3. Working With Groups

Page 15: django-auth-ldap Documentation

CHAPTER 4

User objects

Authenticating against an external source is swell, but Django’s auth module is tightly bound to a user model. Whena user logs in, we have to create a model object to represent them in the database. Because the LDAP search is case-insensitive, the default implementation also searches for existing Django users with an iexact query and new usersare created with lowercase usernames. See get_or_build_user() if you’d like to override this behavior. Seeget_user_model() if you’d like to substitute a proxy model.

By default, lookups on existing users are done using the user model’s USERNAME_FIELD. To lookup by a differentfield, use AUTH_LDAP_USER_LOOKUP_FIELD. When set, the username field is ignored.

When using the default for lookups, the only required field for a user is the username. The default Usermodel can be picky about the characters allowed in usernames, so LDAPBackend includes a pair of hooks,ldap_to_django_username() and django_to_ldap_username(), to translate between LDAP user-names and Django usernames. You may need this, for example, if your LDAP names have periods in them. Youcan subclass LDAPBackend to implement these hooks; by default the username is not modified. User objects thatare authenticated by LDAPBackend will have an ldap_username attribute with the original (LDAP) username.username (or get_username()) will, of course, be the Django username.

Note: Users created by LDAPBackend will have an unusable password set. This will only happen when the useris created, so if you set a valid password in Django, the user will be able to log in through ModelBackend (ifconfigured) even if they are rejected by LDAP. This is not generally recommended, but could be useful as a fail-safefor selected users in case the LDAP server is unavailable.

4.1 Populating Users

You can perform arbitrary population of your user models by adding listeners to the Django signal:django_auth_ldap.backend.populate_user. This signal is sent after the user object has been constructed(but not necessarily saved) and any configured attribute mapping has been applied (see below). You can use this topropagate information from the LDAP directory to the user object any way you like. If you need the user object toexist in the database at this point, you can save it in your signal handler or override get_or_build_user(). Ineither case, the user instance will be saved automatically after the signal handlers are run.

11

Page 16: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

If you need an attribute that isn’t included by default in the LDAP search results, seeAUTH_LDAP_USER_ATTRLIST.

4.2 Easy Attributes

If you just want to copy a few attribute values directly from the user’s LDAP directory entry to their Django user, thesetting, AUTH_LDAP_USER_ATTR_MAP, makes it easy. This is a dictionary that maps user model keys, respectively,to (case-insensitive) LDAP attribute names:

AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn"}

Only string fields can be mapped to attributes. Boolean fields can be defined by group membership:

AUTH_LDAP_USER_FLAGS_BY_GROUP = {"is_active": "cn=active,ou=groups,dc=example,dc=com","is_staff": (

LDAPGroupQuery("cn=staff,ou=groups,dc=example,dc=com") |LDAPGroupQuery("cn=admin,ou=groups,dc=example,dc=com")

),"is_superuser": "cn=superuser,ou=groups,dc=example,dc=com"

}

Values in this dictionary may be simple DNs (as strings), lists or tuples of DNs, or LDAPGroupQuery instances.Lists are converted to queries joined by |.

Remember that if these settings don’t do quite what you want, you can always use the signals described in the previoussection to implement your own logic.

4.3 Updating Users

By default, all mapped user fields will be updated each time the user logs in. To disable this, setAUTH_LDAP_ALWAYS_UPDATE_USER to False. If you need to populate a user outside of the authentica-tion process—for example, to create associated model objects before the user logs in for the first time—youcan call django_auth_ldap.backend.LDAPBackend.populate_user(). You’ll need an instance ofLDAPBackend, which you should feel free to create yourself. populate_user() returns the User or Noneif the user could not be found in LDAP.

from django_auth_ldap.backend import LDAPBackend

user = LDAPBackend().populate_user('alice')if user is None:

raise Exception('No user named alice')

4.4 Direct Attribute Access

If you need to access multi-value attributes or there is some other reason that the above is inadequate, you can alsoaccess the user’s raw LDAP attributes. user.ldap_user is an object with four public properties. The groupproperties are, of course, only valid if groups are configured.

• dn: The user’s distinguished name.

12 Chapter 4. User objects

Page 17: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

• attrs: The user’s LDAP attributes as a dictionary of lists of string values. The dictionaries are modified to usecase-insensitive keys.

• group_dns: The set of groups that this user belongs to, as DNs.

• group_names: The set of groups that this user belongs to, as simple names. These are the names that will beused if AUTH_LDAP_MIRROR_GROUPS is used.

Python-ldap returns all attribute values as utf8-encoded strings. For convenience, this module will try to decode allvalues into Unicode strings. Any string that can not be successfully decoded will be left as-is; this may apply to binaryvalues such as Active Directory’s objectSid.

4.4. Direct Attribute Access 13

Page 18: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

14 Chapter 4. User objects

Page 19: django-auth-ldap Documentation

CHAPTER 5

Permissions

Groups are useful for more than just populating the user’s is_* fields. LDAPBackend would not be completewithout some way to turn a user’s LDAP group memberships into Django model permissions. In fact, there are twoways to do this.

Ultimately, both mechanisms need some way to map LDAP groups to Django groups. Implementations ofLDAPGroupType will have an algorithm for deriving the Django group name from the LDAP group. Clients thatneed to modify this behavior can subclass the LDAPGroupType class. All of the built-in implementations take aname_attr argument to __init__, which specifies the LDAP attribute from which to take the Django groupname. By default, the cn attribute is used.

5.1 Using Groups Directly

The least invasive way to map group permissions is to set AUTH_LDAP_FIND_GROUP_PERMS to True.LDAPBackend will then find all of the LDAP groups that a user belongs to, map them to Django groups, andload the permissions for those groups. You will need to create the Django groups and associate permissions yourself,generally through the admin interface.

To minimize traffic to the LDAP server, LDAPBackend can make use of Django’s cache framework to keep a copyof a user’s LDAP group memberships. To enable this feature, set AUTH_LDAP_CACHE_GROUPS to True. You canalso set AUTH_LDAP_GROUP_CACHE_TIMEOUT to override the timeout of cache entries (in seconds).

AUTH_LDAP_CACHE_GROUPS = TrueAUTH_LDAP_GROUP_CACHE_TIMEOUT = 300

5.2 Group Mirroring

The second way to turn LDAP group memberships into permissions is to mirror the groups themselves. This approachhas some important disadvantages and should be avoided if possible. For one thing, membership will only be updatedwhen the user authenticates, which may be especially inappropriate for sites with long session timeouts.

15

Page 20: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

If AUTH_LDAP_MIRROR_GROUPS is True, then every time a user logs in, LDAPBackend will update the databasewith the user’s LDAP groups. Any group that doesn’t exist will be created and the user’s Django group membershipwill be updated to exactly match their LDAP group membership. If the LDAP server has nested groups, the Djangodatabase will end up with a flattened representation. For group mirroring to have any effect, you of course needModelBackend installed as an authentication backend.

By default, we assume that LDAP is the sole authority on group membership; if you remove a user from a group inLDAP, they will be removed from the corresponding Django group the next time they log in. It is also possible tohave django-auth-ldap ignore some Django groups, presumably because they are managed manually or through someother mechanism. If AUTH_LDAP_MIRROR_GROUPS is a list of group names, we will manage these groups andno others. If AUTH_LDAP_MIRROR_GROUPS_EXCEPT is a list of group names, we will manage all groups exceptthose named; AUTH_LDAP_MIRROR_GROUPS is ignored in this case.

5.3 Non-LDAP Users

LDAPBackend has one more feature pertaining to permissions, which is the ability to handle authorization for usersthat it did not authenticate. For example, you might be using RemoteUserBackend to map externally authenticatedusers to Django users. By setting AUTH_LDAP_AUTHORIZE_ALL_USERS, LDAPBackend will map these usersto LDAP users in the normal way in order to provide authorization information. Note that this does not work withAUTH_LDAP_MIRROR_GROUPS; group mirroring is a feature of authentication, not authorization.

16 Chapter 5. Permissions

Page 21: django-auth-ldap Documentation

CHAPTER 6

Multiple LDAP Configs

New in version 1.1.

You’ve probably noticed that all of the settings for this backend have the prefix AUTH_LDAP_. This is the default,but it can be customized by subclasses of LDAPBackend. The main reason you would want to do this is to createtwo backend subclasses that reference different collections of settings and thus operate independently. For example,you might have two separate LDAP servers that you want to authenticate against. A short example should demonstratethis:

# mypackage.ldap

from django_auth_ldap.backend import LDAPBackend

class LDAPBackend1(LDAPBackend):settings_prefix = "AUTH_LDAP_1_"

class LDAPBackend2(LDAPBackend):settings_prefix = "AUTH_LDAP_2_"

# settings.py

AUTH_LDAP_1_SERVER_URI = "ldap://ldap1.example.com"AUTH_LDAP_1_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

AUTH_LDAP_2_SERVER_URI = "ldap://ldap2.example.com"AUTH_LDAP_2_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

AUTHENTICATION_BACKENDS = ("mypackage.ldap.LDAPBackend1","mypackage.ldap.LDAPBackend2",

)

All of the usual rules apply: Django will attempt to authenticate a user with each backend in turn until one of themsucceeds. When a particular backend successfully authenticates a user, that user will be linked to the backend for theduration of their session.

17

Page 22: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

Note: Due to its global nature, AUTH_LDAP_GLOBAL_OPTIONS ignores the settings prefix. Regardless of howmany backends are installed, this setting is referenced once by its default name at the time we load the ldap module.

18 Chapter 6. Multiple LDAP Configs

Page 23: django-auth-ldap Documentation

CHAPTER 7

Logging

LDAPBackend uses the standard logging module to log debug and warning messages to the logger named'django_auth_ldap'. If you need debug messages to help with configuration issues, you should add a han-dler to this logger. Note that this logger is initialized with a level of NOTSET, so you may need to change the level ofthe logger in order to get debug messages.

import logging

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

19

Page 24: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

20 Chapter 7. Logging

Page 25: django-auth-ldap Documentation

CHAPTER 8

Performance

LDAPBackend is carefully designed not to require a connection to the LDAP service for every request. Of course,this depends heavily on how it is configured. If LDAP traffic or latency is a concern for your deployment, this sectionhas a few tips on minimizing it, in decreasing order of impact.

1. Cache groups. If AUTH_LDAP_FIND_GROUP_PERMS is True, the default behavior is to reload a user’sgroup memberships on every request. This is the safest behavior, as any membership change takes effect im-mediately, but it is expensive. If possible, set AUTH_LDAP_CACHE_GROUPS to True to remove most of thistraffic.

2. Don’t access user.ldap_user.*. Except for ldap_user.dn, these properties are only cached on a per-request basis. If you can propagate LDAP attributes to a User, they will only be updated at login. user.ldap_user.attrs triggers an LDAP connection for every request in which it’s accessed.

3. Use simpler group types. Some grouping mechanisms are more expensive than others. This will often beoutside your control, but it’s important to note that the extra functionality of more complex group types likeNestedGroupOfNamesType is not free and will generally require a greater number and complexity ofLDAP queries.

4. Use direct binding. Binding with AUTH_LDAP_USER_DN_TEMPLATE is a little bit more efficient than re-lying on AUTH_LDAP_USER_SEARCH . Specifically, it saves two LDAP operations (one bind and one search)per login.

21

Page 26: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

22 Chapter 8. Performance

Page 27: django-auth-ldap Documentation

CHAPTER 9

Example Configuration

Here is a complete example configuration from settings.py that exercises nearly all of the features. In thisexample, we’re authenticating against a global pool of users in the directory, but we have a special area set aside forDjango groups (ou=django,ou=groups,dc=example,dc=com). Remember that most of this is optional if you just needsimple authentication. Some default settings and arguments are included for completeness.

import ldapfrom django_auth_ldap.config import LDAPSearch, GroupOfNamesType

# Baseline configuration.AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"

AUTH_LDAP_BIND_DN = "cn=django-agent,dc=example,dc=com"AUTH_LDAP_BIND_PASSWORD = "phlebotinum"AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",

ldap.SCOPE_SUBTREE, "(uid=%(user)s)")# or perhaps:# AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"

# Set up the basic group parameters.AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=django,ou=groups,dc=example,dc=com",

ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)")AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")

# Simple group restrictionsAUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=django,ou=groups,dc=example,dc=com"AUTH_LDAP_DENY_GROUP = "cn=disabled,ou=django,ou=groups,dc=example,dc=com"

# Populate the Django user from the LDAP directory.AUTH_LDAP_USER_ATTR_MAP = {

"first_name": "givenName","last_name": "sn","email": "mail"

}

23

Page 28: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

AUTH_LDAP_USER_FLAGS_BY_GROUP = {"is_active": "cn=active,ou=django,ou=groups,dc=example,dc=com","is_staff": "cn=staff,ou=django,ou=groups,dc=example,dc=com","is_superuser": "cn=superuser,ou=django,ou=groups,dc=example,dc=com"

}

# This is the default, but I like to be explicit.AUTH_LDAP_ALWAYS_UPDATE_USER = True

# Use LDAP group membership to calculate group permissions.AUTH_LDAP_FIND_GROUP_PERMS = True

# Cache group memberships for an hour to minimize LDAP trafficAUTH_LDAP_CACHE_GROUPS = TrueAUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600

# Keep ModelBackend around for per-user permissions and maybe a local# superuser.AUTHENTICATION_BACKENDS = (

'django_auth_ldap.backend.LDAPBackend','django.contrib.auth.backends.ModelBackend',

)

24 Chapter 9. Example Configuration

Page 29: django-auth-ldap Documentation

CHAPTER 10

Reference

10.1 Settings

10.1.1 AUTH_LDAP_ALWAYS_UPDATE_USER

Default: True

If True, the fields of a User object will be updated with the latest values from the LDAP directory every time theuser logs in. Otherwise the User object will only be populated when it is automatically created.

10.1.2 AUTH_LDAP_AUTHORIZE_ALL_USERS

Default: False

If True, LDAPBackend will be able furnish permissions for any Django user, regardless of which backend authen-ticated it.

10.1.3 AUTH_LDAP_BIND_AS_AUTHENTICATING_USER

Default: False

If True, authentication will leave the LDAP connection bound as the authenticating user, rather than forcing it tore-bind with the default credentials after authentication succeeds. This may be desirable if you do not have globalcredentials that are able to access the user’s attributes. django-auth-ldap never stores the user’s password, so this onlyapplies to requests where the user is authenticated. Thus, the downside to this setting is that LDAP results may varybased on whether the user was authenticated earlier in the Django view, which could be surprising to code not directlyconcerned with authentication.

10.1.4 AUTH_LDAP_BIND_DN

Default: '' (Empty string)

25

Page 30: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

The distinguished name to use when binding to the LDAP server (with AUTH_LDAP_BIND_PASSWORD).Use the empty string (the default) for an anonymous bind. To authenticate a user, we will bind with thatuser’s DN and password, but for all other LDAP operations, we will be bound as the DN in this setting.For example, if AUTH_LDAP_USER_DN_TEMPLATE is not set, we’ll use this to search for the user. IfAUTH_LDAP_FIND_GROUP_PERMS is True, we’ll also use it to determine group membership.

10.1.5 AUTH_LDAP_BIND_PASSWORD

Default: '' (Empty string)

The password to use with AUTH_LDAP_BIND_DN .

10.1.6 AUTH_LDAP_CACHE_GROUPS

Default: False

If True, LDAP group membership will be cached using Django’s cache framework. The cache timeout can becustomized with AUTH_LDAP_GROUP_CACHE_TIMEOUT.

10.1.7 AUTH_LDAP_CONNECTION_OPTIONS

Default: {}

A dictionary of options to pass to each connection to the LDAP server via LDAPObject.set_option(). Keysare ldap.OPT_* constants.

10.1.8 AUTH_LDAP_DENY_GROUP

Default: None

The distinguished name of a group; authentication will fail for any user that belongs to this group.

10.1.9 AUTH_LDAP_FIND_GROUP_PERMS

Default: False

If True, LDAPBackend will furnish group permissions based on the LDAP groups the authenticated user belongsto. AUTH_LDAP_GROUP_SEARCH and AUTH_LDAP_GROUP_TYPE must also be set.

10.1.10 AUTH_LDAP_GLOBAL_OPTIONS

Default: {}

A dictionary of options to pass to ldap.set_option(). Keys are ldap.OPT_* constants.

Note: Due to its global nature, this setting ignores the settings prefix. Regardless of how many backends are installed,this setting is referenced once by its default name at the time we load the ldap module.

26 Chapter 10. Reference

Page 31: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

10.1.11 AUTH_LDAP_GROUP_CACHE_TIMEOUT

Default: None

If AUTH_LDAP_CACHE_GROUPS is True, this is the cache timeout for group memberships. If None, the globalcache timeout will be used.

10.1.12 AUTH_LDAP_GROUP_SEARCH

Default: None

An LDAPSearch object that finds all LDAP groups that users might belong to. If your configuration makes anyreferences to LDAP groups, this and AUTH_LDAP_GROUP_TYPE must be set.

10.1.13 AUTH_LDAP_GROUP_TYPE

Default: None

An LDAPGroupType instance describing the type of group returned by AUTH_LDAP_GROUP_SEARCH .

10.1.14 AUTH_LDAP_MIRROR_GROUPS

Default: None

If True, LDAPBackend will mirror a user’s LDAP group membership in the Django database. Any time a userauthenticates, we will create all of their LDAP groups as Django groups and update their Django group membershipto exactly match their LDAP group membership. If the LDAP server has nested groups, the Django database will endup with a flattened representation.

This can also be a list or other collection of group names, in which case we’ll only mirror those groups and leave therest alone. This is ignored if AUTH_LDAP_MIRROR_GROUPS_EXCEPT is set.

10.1.15 AUTH_LDAP_MIRROR_GROUPS_EXCEPT

Default: None

If this is not None, it must be a list or other collection of group names. This will enable group mirroring, except thatwe’ll never change the membership of the indicated groups. AUTH_LDAP_MIRROR_GROUPS is ignored in this case.

10.1.16 AUTH_LDAP_PERMIT_EMPTY_PASSWORD

Default: False

If False (the default), authentication with an empty password will fail immediately, without any LDAP communi-cation. This is a secure default, as some LDAP servers are configured to allow binds to succeed with no password,perhaps at a reduced level of access. If you need to make use of this LDAP feature, you can change this setting toTrue.

10.1. Settings 27

Page 32: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

10.1.17 AUTH_LDAP_REQUIRE_GROUP

Default: None

The distinguished name of a group; authentication will fail for any user that does not belong to this group. This canalso be an LDAPGroupQuery instance.

10.1.18 AUTH_LDAP_SERVER_URI

Default: 'ldap://localhost'

The URI of the LDAP server. This can be any URI that is supported by your underlying LDAP libraries.

10.1.19 AUTH_LDAP_START_TLS

Default: False

If True, each connection to the LDAP server will call start_tls_s() to enable TLS encryption over the standardLDAP port. There are a number of configuration options that can be given to AUTH_LDAP_GLOBAL_OPTIONSthat affect the TLS connection. For example, ldap.OPT_X_TLS_REQUIRE_CERT can be set to ldap.OPT_X_TLS_NEVER to disable certificate verification, perhaps to allow self-signed certificates.

10.1.20 AUTH_LDAP_USER_QUERY_FIELD

Default: None

The field on the user model used to query the authenticating user in the database. If unset, uses the valueof USERNAME_FIELD of the model class. When set, the value used to query is obtained through theAUTH_LDAP_USER_ATTR_MAP.

10.1.21 AUTH_LDAP_USER_ATTRLIST

Default: None

A list of attribute names to load for the authenticated user. Normally, you can ignore this and the LDAP server willsend back all of the attributes of the directory entry. One reason you might need to override this is to get operationalattributes, which are not normally included:

AUTH_LDAP_USER_ATTRLIST = ['*', '+']

10.1.22 AUTH_LDAP_USER_ATTR_MAP

Default: {}

A mapping from User field names to LDAP attribute names. A users’s User object will be populated from his LDAPattributes at login.

28 Chapter 10. Reference

Page 33: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

10.1.23 AUTH_LDAP_USER_DN_TEMPLATE

Default: None

A string template that describes any user’s distinguished name based on the username. This must contain the place-holder %(user)s.

10.1.24 AUTH_LDAP_USER_FLAGS_BY_GROUP

Default: {}

A mapping from boolean User field names to distinguished names of LDAP groups. The corresponding field is set toTrue or False according to whether the user is a member of the group.

Values may be strings for simple group membership tests or LDAPGroupQuery instances for more complex cases.

10.1.25 AUTH_LDAP_USER_SEARCH

Default: None

An LDAPSearch object that will locate a user in the directory. The filter parameter should contain the placeholder%(user)s for the username. It must return exactly one result for authentication to succeed.

10.2 Module Properties

django_auth_ldap.versionThe library’s current version number as a 3-tuple.

django_auth_ldap.version_stringThe library’s current version number as a string.

10.3 Configuration

class django_auth_ldap.config.LDAPSearch

__init__(base_dn, scope, filterstr=’(objectClass=*)’)

Parameters

• base_dn (str) – The distinguished name of the search base.

• scope (int) – One of ldap.SCOPE_*.

• filterstr (str) – An optional filter string (e.g. ‘(objectClass=person)’). In order tobe valid, filterstr must be enclosed in parentheses.

class django_auth_ldap.config.LDAPSearchUnionNew in version 1.1.

__init__(*searches)

Parameters searches (LDAPSearch) – Zero or more LDAPSearch objects. The result ofthe overall search is the union (by DN) of the results of the underlying searches. The prece-dence of the underlying results and the ordering of the final results are both undefined.

10.2. Module Properties 29

Page 34: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

class django_auth_ldap.config.LDAPGroupTypeThe base class for objects that will determine group membership for various LDAP grouping mechanisms.Implementations are provided for common group types or you can write your own. See the source code forsubclassing notes.

__init__(name_attr=’cn’)By default, LDAP groups will be mapped to Django groups by taking the first value of the cn attribute.You can specify a different attribute with name_attr.

class django_auth_ldap.config.PosixGroupTypeA concrete subclass of LDAPGroupType that handles the posixGroup object class. This checks for bothprimary group and group membership.

__init__(name_attr=’cn’)

class django_auth_ldap.config.MemberDNGroupTypeA concrete subclass of LDAPGroupType that handles grouping mechanisms wherein the group object containsa list of its member DNs.

__init__(member_attr, name_attr=’cn’)

Parameters member_attr (str) – The attribute on the group object that contains a list ofmember DNs. ‘member’ and ‘uniqueMember’ are common examples.

class django_auth_ldap.config.NestedMemberDNGroupTypeSimilar to MemberDNGroupType, except this allows groups to contain other groups as members. Grouphierarchies will be traversed to determine membership.

__init__(member_attr, name_attr=’cn’)As above.

class django_auth_ldap.config.GroupOfNamesTypeA concrete subclass of MemberDNGroupType that handles the groupOfNames object class. Equivalent toMemberDNGroupType('member').

__init__(name_attr=’cn’)

class django_auth_ldap.config.NestedGroupOfNamesTypeA concrete subclass of NestedMemberDNGroupType that handles the groupOfNames object class.Equivalent to NestedMemberDNGroupType('member').

__init__(name_attr=’cn’)

class django_auth_ldap.config.GroupOfUniqueNamesTypeA concrete subclass of MemberDNGroupType that handles the groupOfUniqueNames object class.Equivalent to MemberDNGroupType('uniqueMember').

__init__(name_attr=’cn’)

class django_auth_ldap.config.NestedGroupOfUniqueNamesTypeA concrete subclass of NestedMemberDNGroupType that handles the groupOfUniqueNames objectclass. Equivalent to NestedMemberDNGroupType('uniqueMember').

__init__(name_attr=’cn’)

class django_auth_ldap.config.ActiveDirectoryGroupTypeA concrete subclass of MemberDNGroupType that handles Active Directory groups. Equivalent toMemberDNGroupType('member').

__init__(name_attr=’cn’)

30 Chapter 10. Reference

Page 35: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

class django_auth_ldap.config.NestedActiveDirectoryGroupTypeA concrete subclass of NestedMemberDNGroupType that handles Active Directory groups. Equivalent toNestedMemberDNGroupType('member').

__init__(name_attr=’cn’)

class django_auth_ldap.config.OrganizationalRoleGroupTypeA concrete subclass of MemberDNGroupType that handles the organizationalRole object class.Equivalent to MemberDNGroupType('roleOccupant').

__init__(name_attr=’cn’)

class django_auth_ldap.config.NestedOrganizationalRoleGroupTypeA concrete subclass of NestedMemberDNGroupType that handles the organizationalRole objectclass. Equivalent to NestedMemberDNGroupType('roleOccupant').

__init__(name_attr=’cn’)

class django_auth_ldap.config.LDAPGroupQueryRepresents a compound query for group membership.

This can be used to construct an arbitrarily complex group membership query with AND, OR, and NOT logicaloperators. Construct primitive queries with a group DN as the only argument. These queries can then becombined with the &, |, and ~ operators.

This is used by certain settings, including AUTH_LDAP_REQUIRE_GROUP andAUTH_LDAP_USER_FLAGS_BY_GROUP. An example is shown in Limiting Access.

__init__(group_dn)

Parameters group_dn (str) – The distinguished name of a group to test for membership.

10.4 Backend

django_auth_ldap.backend.populate_userThis is a Django signal that is sent when clients should perform additional customization of a User object. It issent after a user has been authenticated and the backend has finished populating it, and just before it is saved. Theclient may take this opportunity to populate additional model fields, perhaps based on ldap_user.attrs.This signal has two keyword arguments: user is the User object and ldap_user is the same as user.ldap_user. The sender is the LDAPBackend class.

django_auth_ldap.backend.ldap_errorThis is a Django signal that is sent when we receive an ldap.LDAPError exception. The signal has threekeyword arguments:

• context: one of 'authenticate', 'get_group_permissions', or 'populate_user', in-dicating which API was being called when the exception was caught.

• user: the Django user being processed (if available).

• exception: the LDAPError object itself.

The sender is the LDAPBackend class (or subclass).

class django_auth_ldap.backend.LDAPBackendLDAPBackend has one method that may be called directly and several that may be overridden in subclasses.

settings_prefixA prefix for all of our Django settings. By default, this is 'AUTH_LDAP_', but subclasses can overridethis. When different subclasses use different prefixes, they can both be installed and operate independently.

10.4. Backend 31

Page 36: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

default_settingsA dictionary of default settings. This is empty in LDAPBackend, but subclasses can populate this withvalues that will override the built-in defaults. Note that the keys should omit the 'AUTH_LDAP_' prefix.

populate_user(username)Populates the Django user for the given LDAP username. This connects to the LDAP directory withthe default credentials and attempts to populate the indicated Django user as if they had just logged in.AUTH_LDAP_ALWAYS_UPDATE_USER is ignored (assumed True).

get_user_model(self)Returns the user model that get_or_build_user() will instantiate. By default, custom user modelswill be respected. Subclasses would most likely override this in order to substitute a proxy model.

authenticate_ldap_user(self, ldap_user, password)Given an LDAP user object and password, authenticates the user and returns a Django user object. SeeCustomizing Authentication.

get_or_build_user(self, username, ldap_user)Given a username and an LDAP user object, this must return a valid Django user model instance. Theusername argument has already been passed through ldap_to_django_username(). You can getinformation about the LDAP user via ldap_user.dn and ldap_user.attrs. The return value mustbe an (instance, created) two-tuple. The instance does not need to be saved.

The default implementation looks for the username with a case-insensitive query; if it’s not found, themodel returned by get_user_model() will be created with the lowercased username. New users willnot be saved to the database until after the django_auth_ldap.backend.populate_user signalhas been sent.

A subclass may override this to associate LDAP users to Django users any way it likes.

ldap_to_django_username(username)Returns a valid Django username based on the given LDAP username (which is what the user enters). Bydefault, username is returned unchanged. This can be overridden by subclasses.

django_to_ldap_username(username)The inverse of ldap_to_django_username(). If this is not symmetrical toldap_to_django_username(), the behavior is undefined.

32 Chapter 10. Reference

Page 37: django-auth-ldap Documentation

CHAPTER 11

Change Log

11.1 1.5.0 - 2018-04-18

• django-auth-ldap is now hosted at https://github.com/django-auth-ldap/django-auth-ldap.

• Removed NISGroupType class. It searched by attribute nisNetgroupTriple, which has no defined EQAULITYrule.

• The python-ldap library is now initialized with bytes_mode=False, requiring all LDAP values to be handledas Unicode text (str in Python 3 and unicode in Python 2), not bytes. For additional information, see thepython-ldap documentation on bytes mode

• Removed deprecated function LDAPBackend.get_or_create_user(). Useget_or_build_user() instead.

11.2 1.4.0 - 2018-03-22

• Honor the attrlist argument to AUTH_LDAP_GROUP_SEARCH

• Backwards incompatible: Removed support for Django < 1.11.

• Support for Python 2.7 and 3.4+ now handled by the same dependency, python-ldap >= 3.0.

11.3 1.3.0 - 2017-11-20

• Backwards incompatible: Removed support for obsolete versions of Django (<=1.7, plus 1.9).

• Delay saving new users as long as possible. This will allow AUTH_LDAP_USER_ATTR_MAP to populaterequired fields before creating a new Django user.

LDAPBackend.get_or_create_user() is now get_or_build_user() to avoid confusion. Theold name may still be overridden for now.

33

Page 38: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

• Support querying by a field other than the username field with AUTH_LDAP_USER_QUERY_FIELD.

• New method authenticate_ldap_user() to provide pre- and post-authenication hooks.

• Add support for Django 2.0.

11.4 1.2.16 - 2017-09-30

• Better cache key sanitizing.

• Improved handling of LDAPError. A case existed where the error would not get caught while loading grouppermissions.

11.5 1.2.15 - 2017-08-17

• Improved documentation for finding the official repository and contributing.

11.6 1.2.14 - 2017-07-24

• Under search/bind mode, the user’s DN will now be cached for performance.

11.7 1.2.13 - 2017-06-19

• Support selective group mirroring with AUTH_LDAP_MIRROR_GROUPS andAUTH_LDAP_MIRROR_GROUPS_EXCEPT.

• Work around Django 1.11 bug with multiple authentication backends.

11.8 1.2.12 - 2017-05-20

• Support for complex group queries via LDAPGroupQuery .

11.9 1.2.11 - 2017-04-22

• Some more descriptive object representations.

• Improved tox.ini organization.

11.10 1.2.9 - 2017-02-14

• Ignore python-ldap documentation and accept ldap.RES_SEARCH_ENTRY from ldap.LDAPObject.result().

34 Chapter 11. Change Log

Page 39: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

11.11 1.2.8 - 2016-04-18

• Add AUTH_LDAP_USER_ATTRLIST to override the set of attributes requested from the LDAP server.

11.12 1.2.7 - 2015-09-29

• Support Python 3 with pyldap.

11.13 1.2.6 - 2015-03-29

• Performance improvements to group mirroring (from Denver Janke).

• Add django_auth_ldap.backend.ldap_error signal for custom handling of LDAPError excep-tions.

• Add django_auth_ldap.backend.LDAPBackend.default_settings for per-subclass defaultsettings.

11.14 1.2.5 - 2015-01-30

• Fix interaction between AUTH_LDAP_AUTHORIZE_ALL_USERS and AUTH_LDAP_USER_SEARCH .

11.15 1.2.4 - 2014-12-28

• Add support for nisNetgroup groups (thanks to Christopher Bartz).

11.16 1.2.3 - 2014-11-18

• Improved escaping for filter strings.

• Accept (and ignore) arbitrary keyword arguments to authenticate().

11.17 1.2.2 - 2014-09-22

• Include test harness in source distribution. Some package maintainers find this helpful.

11.18 1.2.1 - 2014-08-24

• More verbose log messages for authentication failures.

11.11. 1.2.8 - 2016-04-18 35

Page 40: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

11.19 1.2 - 2014-04-10

• django-auth-ldap now provides experimental Python 3 support. Python 2.5 was dropped.

To sum up, django-auth-ldap works with Python 2.6, 2.7, 3.3 and 3.4.

Since python-ldap isn’t making progress toward Python 3, if you’re using Python 3, you need to install a fork:

$ pip install git+https://github.com/rbarrois/python-ldap.git@py3

Thanks to Aymeric Augustin for making this happen.

11.20 1.1.8 - 2014-02-01

• Update LDAPSearchUnion to work for group searches in addition to user searches.

• Tox no longer supports Python 2.5, so our tests now run on 2.6 and 2.7 only.

11.21 1.1.7 - 2013-11-19

• Bug fix: AUTH_LDAP_GLOBAL_OPTIONS could be ignored in some cases (such as populate_user()).

11.22 1.1.5 - 2013-10-25

• Support POSIX group permissions with no gidNumber attribute.

• Support multiple group DNs for *_FLAGS_BY_GROUP.

11.23 1.1.4 - 2013-03-09

• Add support for Django 1.5’s custom user models.

11.24 1.1.3 - 2013-01-05

• Reject empty passwords by default.

Unless AUTH_LDAP_PERMIT_EMPTY_PASSWORD is set to True, LDAPBackend.authenticate() will imme-diately return None if the password is empty. This is technically backwards-incompatible, but it’s a more securedefault for those LDAP servers that are configured such that binds without passwords always succeed.

• Add support for pickling LDAP-authenticated users.

36 Chapter 11. Change Log

Page 41: django-auth-ldap Documentation

CHAPTER 12

License

Copyright (c) 2009, Peter Sagerson All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that thefollowing conditions are met:

• Redistributions of source code must retain the above copyright notice, this list of conditions and the followingdisclaimer.

• Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the follow-ing disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANYEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIESOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENTSHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, IN-CIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITEDTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSI-NESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CON-TRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANYWAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAM-AGE.

37

Page 42: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

38 Chapter 12. License

Page 43: django-auth-ldap Documentation

Python Module Index

ddjango_auth_ldap, 29django_auth_ldap.backend, 31django_auth_ldap.config, 29

39

Page 44: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

40 Python Module Index

Page 45: django-auth-ldap Documentation

Index

Symbols__init__() (django_auth_ldap.config.ActiveDirectoryGroupType

method), 30__init__() (django_auth_ldap.config.GroupOfNamesType

method), 30__init__() (django_auth_ldap.config.GroupOfUniqueNamesType

method), 30__init__() (django_auth_ldap.config.LDAPGroupQuery

method), 31__init__() (django_auth_ldap.config.LDAPGroupType

method), 30__init__() (django_auth_ldap.config.LDAPSearch

method), 29__init__() (django_auth_ldap.config.LDAPSearchUnion

method), 29__init__() (django_auth_ldap.config.MemberDNGroupType

method), 30__init__() (django_auth_ldap.config.NestedActiveDirectoryGroupType

method), 31__init__() (django_auth_ldap.config.NestedGroupOfNamesType

method), 30__init__() (django_auth_ldap.config.NestedGroupOfUniqueNamesType

method), 30__init__() (django_auth_ldap.config.NestedMemberDNGroupType

method), 30__init__() (django_auth_ldap.config.NestedOrganizationalRoleGroupType

method), 31__init__() (django_auth_ldap.config.OrganizationalRoleGroupType

method), 31__init__() (django_auth_ldap.config.PosixGroupType

method), 30

AActiveDirectoryGroupType (class in

django_auth_ldap.config), 30AUTH_LDAP_ALWAYS_UPDATE_USER

setting, 25AUTH_LDAP_AUTHORIZE_ALL_USERS

setting, 25

AUTH_LDAP_BIND_AS_AUTHENTICATING_USERsetting, 25

AUTH_LDAP_BIND_DNsetting, 25

AUTH_LDAP_BIND_PASSWORDsetting, 26

AUTH_LDAP_CACHE_GROUPSsetting, 26

AUTH_LDAP_CONNECTION_OPTIONSsetting, 26

AUTH_LDAP_DENY_GROUPsetting, 26

AUTH_LDAP_FIND_GROUP_PERMSsetting, 26

AUTH_LDAP_GLOBAL_OPTIONSsetting, 26

AUTH_LDAP_GROUP_CACHE_TIMEOUTsetting, 26

AUTH_LDAP_GROUP_SEARCHsetting, 27

AUTH_LDAP_GROUP_TYPEsetting, 27

AUTH_LDAP_MIRROR_GROUPSsetting, 27

AUTH_LDAP_MIRROR_GROUPS_EXCEPTsetting, 27

AUTH_LDAP_PERMIT_EMPTY_PASSWORDsetting, 27

AUTH_LDAP_REQUIRE_GROUPsetting, 27

AUTH_LDAP_SERVER_URIsetting, 28

AUTH_LDAP_START_TLSsetting, 28

AUTH_LDAP_USER_ATTR_MAPsetting, 28

AUTH_LDAP_USER_ATTRLISTsetting, 28

AUTH_LDAP_USER_DN_TEMPLATEsetting, 28

41

Page 46: django-auth-ldap Documentation

django-auth-ldap Documentation, Release 1.5.0

AUTH_LDAP_USER_FLAGS_BY_GROUPsetting, 29

AUTH_LDAP_USER_QUERY_FIELDsetting, 28

AUTH_LDAP_USER_SEARCHsetting, 29

authenticate_ldap_user() (django_auth_ldap.backend.LDAPBackendmethod), 32

Ddjango_auth_ldap (module), 29django_auth_ldap.backend (module), 31django_auth_ldap.config (module), 29django_to_ldap_username()

(django_auth_ldap.backend.LDAPBackendmethod), 32

Gget_or_build_user() (django_auth_ldap.backend.LDAPBackend

method), 32get_user_model() (django_auth_ldap.backend.LDAPBackend

method), 32GroupOfNamesType (class in django_auth_ldap.config),

30GroupOfUniqueNamesType (class in

django_auth_ldap.config), 30

Lldap_error (in module django_auth_ldap.backend), 31ldap_to_django_username()

(django_auth_ldap.backend.LDAPBackendmethod), 32

LDAPBackend (class in django_auth_ldap.backend), 31LDAPBackend.default_settings (in module

django_auth_ldap.backend), 31LDAPBackend.settings_prefix (in module

django_auth_ldap.backend), 31LDAPGroupQuery (class in django_auth_ldap.config), 31LDAPGroupType (class in django_auth_ldap.config), 29LDAPSearch (class in django_auth_ldap.config), 29LDAPSearchUnion (class in django_auth_ldap.config),

29

MMemberDNGroupType (class in

django_auth_ldap.config), 30

NNestedActiveDirectoryGroupType (class in

django_auth_ldap.config), 30NestedGroupOfNamesType (class in

django_auth_ldap.config), 30NestedGroupOfUniqueNamesType (class in

django_auth_ldap.config), 30

NestedMemberDNGroupType (class indjango_auth_ldap.config), 30

NestedOrganizationalRoleGroupType (class indjango_auth_ldap.config), 31

OOrganizationalRoleGroupType (class in

django_auth_ldap.config), 31

Ppopulate_user (in module django_auth_ldap.backend), 31populate_user() (django_auth_ldap.backend.LDAPBackend

method), 32PosixGroupType (class in django_auth_ldap.config), 30

Ssetting

AUTH_LDAP_ALWAYS_UPDATE_USER, 25AUTH_LDAP_AUTHORIZE_ALL_USERS, 25AUTH_LDAP_BIND_AS_AUTHENTICATING_USER,

25AUTH_LDAP_BIND_DN, 25AUTH_LDAP_BIND_PASSWORD, 26AUTH_LDAP_CACHE_GROUPS, 26AUTH_LDAP_CONNECTION_OPTIONS, 26AUTH_LDAP_DENY_GROUP, 26AUTH_LDAP_FIND_GROUP_PERMS, 26AUTH_LDAP_GLOBAL_OPTIONS, 26AUTH_LDAP_GROUP_CACHE_TIMEOUT, 26AUTH_LDAP_GROUP_SEARCH, 27AUTH_LDAP_GROUP_TYPE, 27AUTH_LDAP_MIRROR_GROUPS, 27AUTH_LDAP_MIRROR_GROUPS_EXCEPT, 27AUTH_LDAP_PERMIT_EMPTY_PASSWORD,

27AUTH_LDAP_REQUIRE_GROUP, 27AUTH_LDAP_SERVER_URI, 28AUTH_LDAP_START_TLS, 28AUTH_LDAP_USER_ATTR_MAP, 28AUTH_LDAP_USER_ATTRLIST, 28AUTH_LDAP_USER_DN_TEMPLATE, 28AUTH_LDAP_USER_FLAGS_BY_GROUP, 29AUTH_LDAP_USER_QUERY_FIELD, 28AUTH_LDAP_USER_SEARCH, 29

Vversion (in module django_auth_ldap), 29version_string (in module django_auth_ldap), 29

42 Index