我目前可以使用 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/