index.rst 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. ================================
  2. Django authentication using LDAP
  3. ================================
  4. This authentication backend enables a Django project to authenticate against any
  5. LDAP server. To use it, add :class:`django_auth_ldap.backend.LDAPBackend` to
  6. AUTHENTICATION_BACKENDS. It is not necessary to add `django_auth_ldap` to
  7. INSTALLED_APPLICATIONS unless you would like to run the unit tests. LDAP
  8. configuration can be as simple as a single distinguished name template, but
  9. there are many rich options for working with
  10. :class:`~django.contrib.auth.models.User` objects, groups, and permissions. This
  11. backend depends on the `python-ldap <http://www.python-ldap.org/>`_ module.
  12. .. note::
  13. :class:`~django_auth_ldap.backend.LDAPBackend` does not inherit from
  14. :class:`~django.contrib.auth.backends.ModelBackend`. It is possible to use
  15. :class:`~django_auth_ldap.backend.LDAPBackend` exclusively by configuring it
  16. to draw group membership from the LDAP server. However, if you would like to
  17. assign permissions to individual users or add users to groups within Django,
  18. you'll need to have both backends installed:
  19. .. code-block:: python
  20. AUTHENTICATION_BACKENDS = (
  21. 'django_auth_ldap.backend.LDAPBackend',
  22. 'django.contrib.auth.backends.ModelBackend',
  23. )
  24. Configuring basic authentication
  25. ================================
  26. If your LDAP server isn't running locally on the default port, you'll want to
  27. start by setting :ref:`AUTH_LDAP_SERVER_URI` to point to your server.
  28. .. code-block:: python
  29. AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
  30. That done, the first step is to authenticate a username and password against the
  31. LDAP service. There are two ways to do this, called search/bind and simply bind.
  32. The first one involves connecting to the LDAP server either anonymously or with
  33. a fixed account and searching for the distinguished name of the authenticating
  34. user. Then we can attempt to bind again with the user's password. The second
  35. method is to derive the user's DN from his username and attempt to bind as the
  36. user directly.
  37. Because LDAP searches appear elsewhere in the configuration, the
  38. :class:`~django_auth_ldap.config.LDAPSearch` class is provided to encapsulate
  39. search information. In this case, the filter parameter should contain the
  40. placeholder ``%(user)s``. A simple configuration for the search/bind approach
  41. looks like this (some defaults included for completeness)::
  42. import ldap
  43. from django_auth_ldap.config import LDAPSearch
  44. AUTH_LDAP_BIND_DN = ""
  45. AUTH_LDAP_BIND_PASSWORD = ""
  46. AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
  47. ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
  48. This will perform an anonymous bind, search under
  49. ``"ou=users,dc=example,dc=com"`` for an object with a uid matching the user's
  50. name, and try to bind using that DN and the user's password. The search must
  51. return exactly one result or authentication will fail. If you can't search
  52. anonymously, you can set :ref:`AUTH_LDAP_BIND_DN` to the distinguished name of
  53. an authorized user and :ref:`AUTH_LDAP_BIND_PASSWORD` to the password.
  54. To skip the search phase, set :ref:`AUTH_LDAP_USER_DN_TEMPLATE` to a template
  55. that will produce the authenticating user's DN directly. This template should
  56. have one placeholder, ``%(user)s``. If the previous example had used
  57. ``ldap.SCOPE_ONELEVEL``, the following would be a more straightforward (and
  58. efficient) equivalent::
  59. AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
  60. By default, LDAP connections are unencrypted and make no attempt to protect
  61. sensitive information, such as passwords. When communicating with an LDAP server
  62. on localhost or on a local network, this might be fine. If you need a secure
  63. connection to the LDAP server, you can either use an ``ldaps://`` URL or enable
  64. the StartTLS extension. The latter is generally the preferred mechanism. To
  65. enable StartTLS, set :ref:`AUTH_LDAP_START_TLS` to ``True``::
  66. AUTH_LDAP_START_TLS = True
  67. Working with groups
  68. ===================
  69. Working with groups in LDAP can be a tricky business, mostly because there are
  70. so many different kinds. This module includes an extensible API for working with
  71. any kind of group and includes implementations for the most common ones.
  72. :class:`~django_auth_ldap.config.LDAPGroupType` is a base class whose concrete
  73. subclasses can determine group membership for particular grouping mechanisms.
  74. Three built-in subclasses cover most grouping mechanisms:
  75. * :class:`~django_auth_ldap.config.PosixGroupType`
  76. * :class:`~django_auth_ldap.config.MemberDNGroupType`
  77. * :class:`~django_auth_ldap.config.NestedMemberDNGroupType`
  78. posixGroup objects are somewhat specialized, so they get their own class. The
  79. other two cover mechanisms whereby a group object stores a list of its members
  80. as distinguished names. This includes groupOfNames, groupOfUniqueNames, and
  81. Active Directory groups, among others. The nested variant allows groups to
  82. contain other groups, to as many levels as you like. For convenience and
  83. readability, several trivial subclasses of the above are provided:
  84. * :class:`~django_auth_ldap.config.GroupOfNamesType`
  85. * :class:`~django_auth_ldap.config.NestedGroupOfNamesType`
  86. * :class:`~django_auth_ldap.config.GroupOfUniqueNamesType`
  87. * :class:`~django_auth_ldap.config.NestedGroupOfUniqueNamesType`
  88. * :class:`~django_auth_ldap.config.ActiveDirectoryGroupType`
  89. * :class:`~django_auth_ldap.config.NestedActiveDirectoryGroupType`
  90. To get started, you'll need to provide some basic information about your LDAP
  91. groups. :ref:`AUTH_LDAP_GROUP_SEARCH` is an
  92. :class:`~django_auth_ldap.config.LDAPSearch` object that identifies the set of
  93. relevant group objects. That is, all groups that users might belong to as well
  94. as any others that we might need to know about (in the case of nested groups,
  95. for example). :ref:`AUTH_LDAP_GROUP_TYPE` is an instance of the class
  96. corresponding to the type of group that will be returned by
  97. :ref:`AUTH_LDAP_GROUP_SEARCH`. All groups referenced elsewhere in the
  98. configuration must be of this type and part of the search results.
  99. .. code-block:: python
  100. import ldap
  101. from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
  102. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=example,dc=com",
  103. ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
  104. )
  105. AUTH_LDAP_GROUP_TYPE = GroupOfNamesType()
  106. The simplest use of groups is to limit the users who are allowed to log in. If
  107. :ref:`AUTH_LDAP_REQUIRE_GROUP` is set, then only users who are members of that
  108. group will successfully authenticate::
  109. AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=groups,dc=example,dc=com"
  110. More advanced uses of groups are covered in the next two sections.
  111. User objects
  112. ============
  113. Authenticating against an external source is swell, but Django's auth module is
  114. tightly bound to the :class:`django.contrib.auth.models.User` model. Thus, when
  115. a user logs in, we have to create a :class:`~django.contrib.auth.models.User`
  116. object to represent him in the database.
  117. The only required field for a user is the username, which we obviously have. The
  118. :class:`~django.contrib.auth.models.User` model is picky about the characters
  119. allowed in usernames, so :class:`~django_auth_ldap.backend.LDAPBackend` includes
  120. a pair of hooks,
  121. :meth:`~django_auth_ldap.backend.LDAPBackend.ldap_to_django_username` and
  122. :meth:`~django_auth_ldap.backend.LDAPBackend.django_to_ldap_username`, to
  123. translate between LDAP usernames and Django usernames. You'll need this, for
  124. example, if your LDAP names have periods in them. You can subclass
  125. :class:`~django_auth_ldap.backend.LDAPBackend` to implement these hooks; by
  126. default the username is not modified. :class:`~django.contrib.auth.models.User`
  127. objects that are authenticated by :class:`~django_auth_ldap.backend.LDAPBackend`
  128. will have an :attr:`~django.contrib.auth.models.User.ldap_username` attribute
  129. with the original (LDAP) username.
  130. :attr:`~django.contrib.auth.models.User.username` will, of course, be the Django
  131. username.
  132. LDAP directories tend to contain much more information about users that you may
  133. wish to propagate. A pair of settings, :ref:`AUTH_LDAP_USER_ATTR_MAP` and
  134. :ref:`AUTH_LDAP_PROFILE_ATTR_MAP`, serve to copy directory information into
  135. :class:`~django.contrib.auth.models.User` and profile objects. These are
  136. dictionaries that map user and profile model keys, respectively, to LDAP
  137. attribute names::
  138. AUTH_LDAP_USER_ATTR_MAP = {"first_name": "givenName", "last_name": "sn"}
  139. AUTH_LDAP_PROFILE_ATTR_MAP = {"home_directory": "homeDirectory"}
  140. Only string fields can be mapped to attributes. Boolean fields can be defined by
  141. group membership::
  142. AUTH_LDAP_USER_FLAGS_BY_GROUP = {
  143. "is_active": "cn=active,ou=groups,dc=example,dc=com",
  144. "is_staff": "cn=staff,ou=groups,dc=example,dc=com",
  145. "is_superuser": "cn=superuser,ou=groups,dc=example,dc=com"
  146. }
  147. By default, all mapped user fields will be updated each time the user logs in.
  148. To disable this, set :ref:`AUTH_LDAP_ALWAYS_UPDATE_USER` to ``False``. If you
  149. need to populate a user outside of the authentication process—for example, to
  150. create associated model objects before the user logs in for the first time—you
  151. can call :meth:`django_auth_ldap.backend.LDAPBackend.populate_user`. You'll
  152. need an instance of :class:`~django_auth_ldap.backend.LDAPBackend`, which you
  153. can create yourself if necessary.
  154. If you need to access multi-value attributes or there is some other reason that
  155. the above is inadequate, you can also access the user's raw LDAP attributes.
  156. ``user.ldap_user`` is an object with two public properties:
  157. * ``dn``: The user's distinguished name.
  158. * ``attrs``: The user's LDAP attributes as a dictionary of lists of string
  159. values.
  160. Python-ldap returns all attribute values as utf8-encoded strings. For
  161. convenience, this module will try to decode all values into Unicode strings. Any
  162. string that can not be successfully decoded will be left as-is; this may apply
  163. to binary values such as Active Directory's objectSid.
  164. .. note::
  165. Users created by :class:`~django_auth_ldap.backend.LDAPBackend` will have an
  166. unusable password set. This will only happen when the user is created, so if
  167. you set a valid password in Django, the user will be able to log in through
  168. :class:`~django.contrib.auth.backends.ModelBackend` (if configured) even if
  169. he is rejected by LDAP. This is not generally recommended, but could be
  170. useful as a fail-safe for selected users in case the LDAP server is
  171. unavailable.
  172. Permissions
  173. ===========
  174. Groups are useful for more than just populating the user's ``is_*`` fields.
  175. :class:`~django_auth_ldap.backend.LDAPBackend` would not be complete without
  176. some way to turn a user's LDAP group memberships into Django model permissions.
  177. In fact, there are two ways to do this.
  178. Ultimately, both mechanisms need some way to map LDAP groups to Django groups.
  179. Implementations of :class:`~django_auth_ldap.config.LDAPGroupType` will have an
  180. algorithm for deriving the Django group name from the LDAP group. Clients that
  181. need to modify this behavior can subclass the
  182. :class:`~django_auth_ldap.config.LDAPGroupType` class. All of the built-in
  183. implementations take a ``name_attr`` argument to ``__init__``, which
  184. specifies the LDAP attribute from which to take the Django group name. By
  185. default, the ``cn`` attribute is used.
  186. The least invasive way to map group permissions is to set
  187. :ref:`AUTH_LDAP_FIND_GROUP_PERMS` to ``True``.
  188. :class:`~django_auth_ldap.backend.LDAPBackend` will then find all of the LDAP
  189. groups that a user belongs to, map them to Django groups, and load the
  190. permissions for those groups. You will need to create the Django groups
  191. yourself, generally through the admin interface.
  192. To minimize traffic to the LDAP server,
  193. :class:`~django_auth_ldap.backend.LDAPBackend` can make use of Django's cache
  194. framework to keep a copy of a user's LDAP group memberships. To enable this
  195. feature, set :ref:`AUTH_LDAP_CACHE_GROUPS` to ``True``. You can also set
  196. :ref:`AUTH_LDAP_GROUP_CACHE_TIMEOUT` to override the timeout of cache entries
  197. (in seconds).
  198. .. code-block:: python
  199. AUTH_LDAP_CACHE_GROUPS = True
  200. AUTH_LDAP_GROUP_CACHE_TIMEOUT = 300
  201. The second way to turn LDAP group memberships into permissions is to mirror the
  202. groups themselves. If :ref:`AUTH_LDAP_MIRROR_GROUPS` is ``True``, then every
  203. time a user logs in, :class:`~django_auth_ldap.backend.LDAPBackend` will update
  204. the database with the user's LDAP groups. Any group that doesn't exist will be
  205. created and the user's Django group membership will be updated to exactly match
  206. his LDAP group membership. Note that if the LDAP server has nested groups, the
  207. Django database will end up with a flattened representation.
  208. This approach has two main differences from :ref:`AUTH_LDAP_FIND_GROUP_PERMS`.
  209. First, :ref:`AUTH_LDAP_FIND_GROUP_PERMS` will query for LDAP group membership
  210. either for every request or according to the cache timeout. With group
  211. mirroring, membership will be updated when the user authenticates. This may not
  212. be appropriate for sites with long session timeouts. The second difference is
  213. that with :ref:`AUTH_LDAP_FIND_GROUP_PERMS`, there is no way for clients to
  214. determine a user's group memberships, only their permissions. If you want to
  215. make decisions based directly on group membership, you'll have to mirror the
  216. groups.
  217. :class:`~django_auth_ldap.backend.LDAPBackend` has one more feature pertaining
  218. to permissions, which is the ability to handle authorization for users that it
  219. did not authenticate. For example, you might be using Django's RemoteUserBackend
  220. to map externally authenticated users to Django users. By setting
  221. :ref:`AUTH_LDAP_AUTHORIZE_ALL_USERS`,
  222. :class:`~django_auth_ldap.backend.LDAPBackend` will map these users to LDAP
  223. users in the normal way in order to provide authorization information. Note that
  224. this does *not* work with :ref:`AUTH_LDAP_MIRROR_GROUPS`; group mirroring is a
  225. feature of authentication, not authorization.
  226. Logging
  227. =======
  228. :class:`~django_auth_ldap.backend.LDAPBackend` uses the standard logging module
  229. to log debug and warning messages to the logger named ``'django_auth_ldap'``. If
  230. you need debug messages to help with configuration issues, you should add a
  231. handler to this logger. Note that this logger is initialized with a level of
  232. NOTSET, so you may need to change the level of the logger in order to get debug
  233. messages.
  234. .. code-block:: python
  235. import logging
  236. logger = logging.getLogger('django_auth_ldap')
  237. logger.addHandler(logging.StreamHandler())
  238. logger.setLevel(logging.DEBUG)
  239. More options
  240. ============
  241. Miscellaneous settings for :class:`~django_auth_ldap.backend.LDAPBackend`:
  242. * :ref:`AUTH_LDAP_GLOBAL_OPTIONS`: A dictionary of options to pass to
  243. python-ldap via ``ldap.set_option()``.
  244. * :ref:`AUTH_LDAP_CONNECTION_OPTIONS`: A dictionary of options to pass to
  245. each LDAPObject instance via ``LDAPObject.set_option()``.
  246. Performance
  247. ===========
  248. :class:`~django_auth_ldap.backend.LDAPBackend` is carefully designed not to
  249. require a connection to the LDAP service for every request. Of course, this
  250. depends heavily on how it is configured. If LDAP traffic or latency is a concern
  251. for your deployment, this section has a few tips on minimizing it, in decreasing
  252. order of impact.
  253. #. **Cache groups**. If :ref:`AUTH_LDAP_FIND_GROUP_PERMS` is ``True``, the
  254. default behavior is to reload a user's group memberships on every
  255. request. This is the safest behavior, as any membership change takes
  256. effect immediately, but it is expensive. If possible, set
  257. :ref:`AUTH_LDAP_CACHE_GROUPS` to ``True`` to remove most of this traffic.
  258. Alternatively, you might consider using :ref:`AUTH_LDAP_MIRROR_GROUPS`
  259. and relying on :class:`~django.contrib.auth.backends.ModelBackend` to
  260. supply group permissions.
  261. #. **Don't access user.ldap_user.***. These properties are only cached
  262. on a per-request basis. If you can propagate LDAP attributes to a
  263. :class:`~django.contrib.auth.models.User` or profile object, they will
  264. only be updated at login. ``user.ldap_user.attrs`` triggers an LDAP
  265. connection for every request in which it's accessed. If you're not using
  266. :ref:`AUTH_LDAP_USER_DN_TEMPLATE`, then accessing ``user.ldap_user.dn``
  267. will also trigger an LDAP connection.
  268. #. **Use simpler group types**. Some grouping mechanisms are more expensive
  269. than others. This will often be outside your control, but it's important
  270. to note that the extra functionality of more complex group types like
  271. :class:`~django_auth_ldap.config.NestedGroupOfNamesType` is not free and
  272. will generally require a greater number and complexity of LDAP queries.
  273. #. **Use direct binding**. Binding with
  274. :ref:`AUTH_LDAP_USER_DN_TEMPLATE` is a little bit more efficient than
  275. relying on :ref:`AUTH_LDAP_USER_SEARCH`. Specifically, it saves two LDAP
  276. operations (one bind and one search) per login.
  277. Example configuration
  278. =====================
  279. Here is a complete example configuration from :file:`settings.py` that exercises
  280. nearly all of the features. In this example, we're authenticating against a
  281. global pool of users in the directory, but we have a special area set aside for
  282. Django groups (ou=django,ou=groups,dc=example,dc=com). Remember that most of
  283. this is optional if you just need simple authentication. Some default settings
  284. and arguments are included for completeness.
  285. .. code-block:: python
  286. import ldap
  287. from django_auth_ldap.config import LDAPSearch, GroupOfNamesType
  288. # Baseline configuration.
  289. AUTH_LDAP_SERVER_URI = "ldap://ldap.example.com"
  290. AUTH_LDAP_BIND_DN = "cn=django-agent,dc=example,dc=com"
  291. AUTH_LDAP_BIND_PASSWORD = "phlebotinum"
  292. AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",
  293. ldap.SCOPE_SUBTREE, "(uid=%(user)s)")
  294. # or perhaps:
  295. # AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s,ou=users,dc=example,dc=com"
  296. # Set up the basic group parameters.
  297. AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=django,ou=groups,dc=example,dc=com",
  298. ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)"
  299. )
  300. AUTH_LDAP_GROUP_TYPE = GroupOfNamesType(name_attr="cn")
  301. # Only users in this group can log in.
  302. AUTH_LDAP_REQUIRE_GROUP = "cn=enabled,ou=django,ou=groups,dc=example,dc=com"
  303. # Populate the Django user from the LDAP directory.
  304. AUTH_LDAP_USER_ATTR_MAP = {
  305. "first_name": "givenName",
  306. "last_name": "sn",
  307. "email": "mail"
  308. }
  309. AUTH_LDAP_PROFILE_ATTR_MAP = {
  310. "employee_number": "employeeNumber"
  311. }
  312. AUTH_LDAP_USER_FLAGS_BY_GROUP = {
  313. "is_active": "cn=active,ou=django,ou=groups,dc=example,dc=com",
  314. "is_staff": "cn=staff,ou=django,ou=groups,dc=example,dc=com",
  315. "is_superuser": "cn=superuser,ou=django,ou=groups,dc=example,dc=com"
  316. }
  317. # This is the default, but I like to be explicit.
  318. AUTH_LDAP_ALWAYS_UPDATE_USER = True
  319. # Use LDAP group membership to calculate group permissions.
  320. AUTH_LDAP_FIND_GROUP_PERMS = True
  321. # Cache group memberships for an hour to minimize LDAP traffic
  322. AUTH_LDAP_CACHE_GROUPS = True
  323. AUTH_LDAP_GROUP_CACHE_TIMEOUT = 3600
  324. # Keep ModelBackend around for per-user permissions and maybe a local
  325. # superuser.
  326. AUTHENTICATION_BACKENDS = (
  327. 'django_auth_ldap.backend.LDAPBackend',
  328. 'django.contrib.auth.backends.ModelBackend',
  329. )
  330. Reference
  331. =========
  332. Settings
  333. --------
  334. .. _AUTH_LDAP_ALWAYS_UPDATE_USER:
  335. AUTH_LDAP_ALWAYS_UPDATE_USER
  336. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  337. Default: ``True``
  338. If ``True``, the fields of a :class:`~django.contrib.auth.models.User` object
  339. will be updated with the latest values from the LDAP directory every time the
  340. user logs in. Otherwise the :class:`~django.contrib.auth.models.User` object
  341. will only be populated when it is automatically created.
  342. .. _AUTH_LDAP_AUTHORIZE_ALL_USERS:
  343. AUTH_LDAP_AUTHORIZE_ALL_USERS
  344. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  345. Default: ``False``
  346. If ``True``, :class:`~django_auth_ldap.backend.LDAPBackend` will be able furnish
  347. permissions for any Django user, regardless of which backend authenticated it.
  348. .. _AUTH_LDAP_BIND_DN:
  349. AUTH_LDAP_BIND_DN
  350. ~~~~~~~~~~~~~~~~~
  351. Default: ``''`` (Empty string)
  352. The distinguished name to use when binding to the LDAP server (with
  353. :ref:`AUTH_LDAP_BIND_PASSWORD`). Use the empty string (the default) for an
  354. anonymous bind. To authenticate a user, we will bind with that user's DN and
  355. password, but for all other LDAP operations, we will be bound as the DN in this
  356. setting. For example, if :ref:`AUTH_LDAP_USER_DN_TEMPLATE` is not set, we'll use
  357. this to search for the user. If :ref:`AUTH_LDAP_FIND_GROUP_PERMS` is ``True``,
  358. we'll also use it to determine group membership on subsequent requests.
  359. .. _AUTH_LDAP_BIND_PASSWORD:
  360. AUTH_LDAP_BIND_PASSWORD
  361. ~~~~~~~~~~~~~~~~~~~~~~~
  362. Default: ``''`` (Empty string)
  363. The password to use with :ref:`AUTH_LDAP_BIND_DN`.
  364. .. _AUTH_LDAP_CACHE_GROUPS:
  365. AUTH_LDAP_CACHE_GROUPS
  366. ~~~~~~~~~~~~~~~~~~~~~~
  367. Default: ``False``
  368. If ``True``, LDAP group membership will be cached using Django's cache
  369. framework. The cache timeout can be customized with
  370. :ref:`AUTH_LDAP_GROUP_CACHE_TIMEOUT`.
  371. .. _AUTH_LDAP_CONNECTION_OPTIONS:
  372. AUTH_LDAP_CONNECTION_OPTIONS
  373. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  374. Default: ``{}``
  375. A dictionary of options to pass to each connection to the LDAP server via
  376. ``LDAPObject.set_option()``. Keys are ``ldap.OPT_*`` constants.
  377. .. _AUTH_LDAP_GROUP_CACHE_TIMEOUT:
  378. AUTH_LDAP_GROUP_CACHE_TIMEOUT
  379. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  380. Default: ``None``
  381. If :ref:`AUTH_LDAP_CACHE_GROUPS` is ``True``, this is the cache timeout for
  382. group memberships. If ``None``, the global cache timeout will be used.
  383. .. _AUTH_LDAP_FIND_GROUP_PERMS:
  384. AUTH_LDAP_FIND_GROUP_PERMS
  385. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  386. Default: ``False``
  387. If ``True``, :class:`~django_auth_ldap.backend.LDAPBackend` will furnish group
  388. permissions based on the LDAP groups the authenticated user belongs to.
  389. :ref:`AUTH_LDAP_GROUP_SEARCH` and :ref:`AUTH_LDAP_GROUP_TYPE` must also be set.
  390. .. _AUTH_LDAP_GLOBAL_OPTIONS:
  391. AUTH_LDAP_GLOBAL_OPTIONS
  392. ~~~~~~~~~~~~~~~~~~~~~~~~
  393. Default: ``{}``
  394. A dictionary of options to pass to ``ldap.set_option()``. Keys are
  395. ``ldap.OPT_*`` constants.
  396. .. _AUTH_LDAP_GROUP_SEARCH:
  397. AUTH_LDAP_GROUP_SEARCH
  398. ~~~~~~~~~~~~~~~~~~~~~~
  399. Default: ``None``
  400. An :class:`~django_auth_ldap.config.LDAPSearch` object that finds all LDAP
  401. groups that users might belong to. If your configuration makes any references to
  402. LDAP groups, this and :ref:`AUTH_LDAP_GROUP_TYPE` must be set.
  403. .. _AUTH_LDAP_GROUP_TYPE:
  404. AUTH_LDAP_GROUP_TYPE
  405. ~~~~~~~~~~~~~~~~~~~~
  406. Default: ``None``
  407. An :class:`~django_auth_ldap.config.LDAPGroupType` instance describing the type
  408. of group returned by :ref:`AUTH_LDAP_GROUP_SEARCH`.
  409. .. _AUTH_LDAP_MIRROR_GROUPS:
  410. AUTH_LDAP_MIRROR_GROUPS
  411. ~~~~~~~~~~~~~~~~~~~~~~~
  412. Default: ``False``
  413. If ``True``, :class:`~django_auth_ldap.backend.LDAPBackend` will mirror a user's
  414. LDAP group membership in the Django database. Any time a user authenticates, we
  415. will create all of his LDAP groups as Django groups and update his Django group
  416. membership to exactly match his LDAP group membership. If the LDAP server has
  417. nested groups, the Django database will end up with a flattened representation.
  418. .. _AUTH_LDAP_PROFILE_ATTR_MAP:
  419. AUTH_LDAP_PROFILE_ATTR_MAP
  420. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  421. Default: ``{}``
  422. A mapping from user profile field names to LDAP attribute names. A user's
  423. profile will be populated from his LDAP attributes at login.
  424. .. _AUTH_LDAP_REQUIRE_GROUP:
  425. AUTH_LDAP_REQUIRE_GROUP
  426. ~~~~~~~~~~~~~~~~~~~~~~~
  427. Default: ``None``
  428. The distinguished name of a group that a user must belong to in order to
  429. successfully authenticate.
  430. .. _AUTH_LDAP_SERVER_URI:
  431. AUTH_LDAP_SERVER_URI
  432. ~~~~~~~~~~~~~~~~~~~~
  433. Default: ``ldap://localhost``
  434. The URI of the LDAP server. This can be any URI that is supported by your
  435. underlying LDAP libraries.
  436. .. _AUTH_LDAP_START_TLS:
  437. AUTH_LDAP_START_TLS
  438. ~~~~~~~~~~~~~~~~~~~
  439. Default: ``False``
  440. If ``True``, each connection to the LDAP server will call start_tls to enable
  441. TLS encryption over the standard LDAP port. There are a number of configuration
  442. options that can be given to :ref:`AUTH_LDAP_GLOBAL_OPTIONS` that affect the
  443. TLS connection. For example, ``ldap.OPT_X_TLS_REQUIRE_CERT`` can be set to
  444. ``ldap.OPT_X_TLS_NEVER`` to disable certificate verification, perhaps to allow
  445. self-signed certificates.
  446. .. _AUTH_LDAP_USER_ATTR_MAP:
  447. AUTH_LDAP_USER_ATTR_MAP
  448. ~~~~~~~~~~~~~~~~~~~~~~~
  449. Default: ``{}``
  450. A mapping from :class:`~django.contrib.auth.models.User` field names to LDAP
  451. attribute names. A users's :class:`~django.contrib.auth.models.User` object will
  452. be populated from his LDAP attributes at login.
  453. .. _AUTH_LDAP_USER_DN_TEMPLATE:
  454. AUTH_LDAP_USER_DN_TEMPLATE
  455. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  456. Default: ``None``
  457. A string template that describes any user's distinguished name based on the
  458. username. This must contain the placeholder ``%(user)s``.
  459. .. _AUTH_LDAP_USER_FLAGS_BY_GROUP:
  460. AUTH_LDAP_USER_FLAGS_BY_GROUP
  461. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  462. Default: ``{}``
  463. A mapping from boolean :class:`~django.contrib.auth.models.User` field names to
  464. distinguished names of LDAP groups. The corresponding field is set to ``True``
  465. or ``False`` according to whether the user is a member of the group.
  466. .. _AUTH_LDAP_USER_SEARCH:
  467. AUTH_LDAP_USER_SEARCH
  468. ~~~~~~~~~~~~~~~~~~~~~
  469. Default: ``None``
  470. An :class:`~django_auth_ldap.config.LDAPSearch` object that will locate a user
  471. in the directory. The filter parameter should contain the placeholder
  472. ``%(user)s`` for the username. It must return exactly one result for
  473. authentication to succeed.
  474. Configuration
  475. -------------
  476. .. module:: django_auth_ldap.config
  477. .. class:: LDAPSearch
  478. .. method:: __init__(base_dn, scope, filterstr='(objectClass=*)')
  479. * ``base_dn``: The distinguished name of the search base.
  480. * ``scope``: One of ``ldap.SCOPE_*``.
  481. * ``filterstr``: An optional filter string (e.g. '(objectClass=person)').
  482. In order to be valid, ``filterstr`` must be enclosed in parentheses.
  483. .. class:: LDAPGroupType
  484. The base class for objects that will determine group membership for various
  485. LDAP grouping mechanisms. Implementations are provided for common group
  486. types or you can write your own. See the source code for subclassing notes.
  487. .. method:: __init__(name_attr='cn')
  488. By default, LDAP groups will be mapped to Django groups by taking the
  489. first value of the cn attribute. You can specify a different attribute
  490. with ``name_attr``.
  491. .. class:: PosixGroupType
  492. A concrete subclass of :class:`~django_auth_ldap.config.LDAPGroupType` that
  493. handles the ``posixGroup`` object class. This checks for both primary group
  494. and group membership.
  495. .. method:: __init__(name_attr='cn')
  496. .. class:: MemberDNGroupType
  497. A concrete subclass of
  498. :class:`~django_auth_ldap.config.LDAPGroupType` that handles grouping
  499. mechanisms wherein the group object contains a list of its member DNs.
  500. .. method:: __init__(member_attr, name_attr='cn')
  501. * ``member_attr``: The attribute on the group object that contains a
  502. list of member DNs. 'member' and 'uniqueMember' are common examples.
  503. .. class:: NestedMemberDNGroupType
  504. Similar to :class:`~django_auth_ldap.config.MemberDNGroupType`, except this
  505. allows groups to contain other groups as members. Group hierarchies will be
  506. traversed to determine membership.
  507. .. method:: __init__(member_attr, name_attr='cn')
  508. As above.
  509. .. class:: GroupOfNamesType
  510. A concrete subclass of :class:`~django_auth_ldap.config.MemberDNGroupType`
  511. that handles the ``groupOfNames`` object class. Equivalent to
  512. ``MemberDNGroupType('member')``.
  513. .. method:: __init__(name_attr='cn')
  514. .. class:: NestedGroupOfNamesType
  515. A concrete subclass of
  516. :class:`~django_auth_ldap.config.NestedMemberDNGroupType` that handles the
  517. ``groupOfNames`` object class. Equivalent to
  518. ``NestedMemberDNGroupType('member')``.
  519. .. method:: __init__(name_attr='cn')
  520. .. class:: GroupOfUniqueNamesType
  521. A concrete subclass of :class:`~django_auth_ldap.config.MemberDNGroupType`
  522. that handles the ``groupOfUniqueNames`` object class. Equivalent to
  523. ``MemberDNGroupType('uniqueMember')``.
  524. .. method:: __init__(name_attr='cn')
  525. .. class:: NestedGroupOfUniqueNamesType
  526. A concrete subclass of
  527. :class:`~django_auth_ldap.config.NestedMemberDNGroupType` that handles the
  528. ``groupOfUniqueNames`` object class. Equivalent to
  529. ``NestedMemberDNGroupType('uniqueMember')``.
  530. .. method:: __init__(name_attr='cn')
  531. .. class:: ActiveDirectoryGroupType
  532. A concrete subclass of :class:`~django_auth_ldap.config.MemberDNGroupType`
  533. that handles Active Directory groups. Equivalent to
  534. ``MemberDNGroupType('member')``.
  535. .. method:: __init__(name_attr='cn')
  536. .. class:: NestedActiveDirectoryGroupType
  537. A concrete subclass of
  538. :class:`~django_auth_ldap.config.NestedMemberDNGroupType` that handles
  539. Active Directory groups. Equivalent to
  540. ``NestedMemberDNGroupType('member')``.
  541. .. method:: __init__(name_attr='cn')
  542. Backend
  543. -------
  544. .. module:: django_auth_ldap.backend
  545. .. class:: LDAPBackend
  546. :class:`~django_auth_ldap.backend.LDAPBackend` has one method that may be
  547. called directly and several that may be overridden in subclasses.
  548. .. method:: populate_user(username)
  549. Populates the Django user for the given LDAP username. This connects to
  550. the LDAP directory with the default credentials and attempts to populate
  551. the indicated Django user as if they had just logged in.
  552. :ref:`AUTH_LDAP_ALWAYS_UPDATE_USER` is ignored (assumed ``True``).
  553. .. method:: get_or_create_user(self, username, ldap_user)
  554. Given a username and an LDAP user object, this must return the
  555. associated Django User object. The ``username`` argument has already
  556. been passed through
  557. :meth:`~django_auth_ldap.backend.LDAPBackend.ldap_to_django_username`.
  558. You can get information about the LDAP user via ``ldap_user.dn`` and
  559. ``ldap_user.attrs``. The return value must be the same as
  560. ``User.objects.get_or_create()``: a (User, created) two-tuple.
  561. The default implementation simply calls ``User.objects.get_or_create()``
  562. with the username. Subclasses are welcome to associate LDAP users to
  563. Django users any way they like.
  564. .. method:: ldap_to_django_username(username)
  565. Returns a valid Django username based on the given LDAP username (which
  566. is what the user enters). By default, ``username`` is returned
  567. unchanged. This can be overriden by subclasses.
  568. .. method:: django_to_ldap_username(username)
  569. The inverse of
  570. :meth:`~django_auth_ldap.backend.LDAPBackend.ldap_to_django_username`.
  571. If this is not symmetrical to
  572. :meth:`~django_auth_ldap.backend.LDAPBackend.ldap_to_django_username`,
  573. the behavior is undefined.
  574. License
  575. =======
  576. Copyright (c) 2009, Peter Sagerson
  577. All rights reserved.
  578. Redistribution and use in source and binary forms, with or without modification,
  579. are permitted provided that the following conditions are met:
  580. - Redistributions of source code must retain the above copyright notice, this
  581. list of conditions and the following disclaimer.
  582. - Redistributions in binary form must reproduce the above copyright notice, this
  583. list of conditions and the following disclaimer in the documentation and/or
  584. other materials provided with the distribution.
  585. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  586. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  587. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  588. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  589. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  590. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  591. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  592. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  593. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  594. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.