python - 使用 LDAP 和本地帐户进行 Django Auth

标签 python django ldap

我目前可以使用 Django 和 LDAP。但是,我想将 LDAP 身份验证限制为仅本地帐户数据库中的帐户。 即,如果不存在本地帐户,则拒绝发生访问/LDAP 身份验证。

通过查看 LDAPSearch 中的选项,我无法找到提供此功能的直接选项。关于如何实现这一目标有什么想法吗?

基于 LDAP OU 的限制不是基于现有 LDAP 地址结构的选项。

谢谢

最佳答案

felix001评论中指出,项目文档描述了一个标志AUTH_LDAP_NO_NEW_USERS :

Prevent the creation of new users during authentication. Any users not already in the Django user database will not be able to login.

在设置中启用它会打开所需的行为:

# settings.py

...

AUTH_LDAP_NO_NEW_USERS = True

但是,当前发布的 1.7.0 版本中不包含此功能,因此需要向后移植。我能想到的侵入性最小的实现是:

# myapp/backend.py

from django_auth_ldap import backend as ldap_backend


# backport for AUTH_LDAP_NO_NEW_USERS setting
ldap_backend.LDAPSettings.defaults.update(NO_NEW_USERS=False)


class MyLDAPBackend(ldap_backend.LDAPBackend):

    def get_or_build_user(self, username, ldap_user):
        user, built = super().get_or_build_user(username, ldap_user)
        if self.settings.NO_NEW_USERS and built:  # user was not found in local db and created instead
            raise ldap_user.AuthenticationFailed(
                f'username {username} does not exist in local DB.'
            )
        return user, built

在设置中激活 AUTH_LDAP_NO_NEW_USERS 并暂时使用自定义后端而不是 LDAPBackend:

# myapp/settings.py

AUTH_LDAP_NO_NEW_USERS = True
AUTHENTICATION_BACKENDS += ('myapp.backend.MyLDAPBackend',)

删除向后移植也很容易:一旦发布了 django-auth-ldap 的下一个版本,您唯一需要适应的是 AUTHENTICATION_BACKENDS 元组(当然,删除 myapp/backend.py 模块)。

关于python - 使用 LDAP 和本地帐户进行 Django Auth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55828292/

相关文章:

python - uWSGI 无法识别 --http 或 --wsgi-file 选项

与管理器相关的 Django 重复查询

python - 提交后如何仅清除表单中的特定字段?

javax.naming.directory.BasicAttributes.put() 方法 : is there a way to create an LDAP entry with 2 identical LDAP attributes at creation time?

python - 如何在python数据表中填充空值?

python - 为什么我的 "total"变量没有定义?

Python 编程 : Need to add spaces between character in a split string

python - Django:通过注释字段的总和来排序查询集?

java - 如何使用 unboundid-ldap-sdp 导入 ldif 文件?

postgresql - Postgres LDAP 身份验证