【问题标题】:Django Authentication Ldap Full exampleDjango Authentication Ldap 完整示例
【发布时间】:2019-02-06 09:04:32
【问题描述】:

我部分理解了 Django Ldap 身份验证。谁能给出开发使用 Django Authentication Ldap 的非常基本的应用程序的完整示例。

我浏览了这个resource 并试图理解很多事情,但我仍然无法理解如何在实现中使用它。如何创建将与 LdapBackend 类一起使用的用户模型,以及如何 在 authenticate() 方法等中写很多东西。

【问题讨论】:

    标签: django ldap django-auth-ldap


    【解决方案1】:

    Here 您可以看到一个完整的示例,非常有指导性地展示了如何创建自定义LDAPBackend

    您需要在settings.py 中配置您的LDAP 设置(如您发布的链接所示)并将您的LDAPBackend 添加到AUTHENTICATION_BACKENDS。您可以使用提供的默认 LDAPBackend 或创建自定义的并使用它。

    使用django-auth-ldap提供的默认LDAPBackend

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

    如果您需要为身份验证添加额外的逻辑,请使用自定义 LDAPBackend

    AUTHENTICATION_BACKENDS = (
        'accounts.backends.MyLDAPBackend',
        'django.contrib.auth.backends.ModelBackend',
    )
    

    然后在accounts/backends.py:

    from django_auth_ldap.backend import LDAPBackend
    
    class MyLDAPBackend(LDAPBackend):
        """ A custom LDAP authentication backend """
    
        def authenticate(self, username, password):
            """ Overrides LDAPBackend.authenticate to add custom logic """
    
            user = LDAPBackend().authenticate(self, username, password)
    
            """ Add custom logic here """
    
            return user
    

    查看上面链接的示例以获取更多详细信息。

    如果您是 LDAP 新手,我建议您在有关此主题的另一个问题中查看 this answer(以及另一个)。


    更新 django-auth-ldap 的新版本

    感谢@wolf2600 指出,现在您需要覆盖authenticate_ldap_user 而不是authenticate

    【讨论】:

      【解决方案2】:

      注意:django_auth_ldap 的语法已更改。除了覆盖authenticate,您需要覆盖authenticate_ldap_user

      https://django-auth-ldap.readthedocs.io/en/latest/custombehavior.html

          def authenticate_ldap_user(self, username, password):
              """ Overrides LDAPBackend.authenticate to save user password in django """
              user = LDAPBackend.authenticate_ldap_user(self, username, password)
      
              # If user has successfully logged in, save password in django database
              if user:
                  user.set_password(password)
                  user.save()
      
              return user
      

      我一直在踢自己几个小时(咳嗽几天咳嗽),想知道为什么直到我发现 readthedocs.io 页面才调用我的自定义 authenticate

      【讨论】:

        猜你喜欢
        • 2014-03-13
        • 1970-01-01
        • 2013-01-03
        • 2023-03-22
        • 2022-10-15
        • 2012-08-22
        • 2011-03-21
        • 2012-10-12
        • 2015-05-17
        相关资源
        最近更新 更多