使用 LDAP 和本地帐户的 Django 身份验证
Django Auth with LDAP and Local Accounts
我目前正在使用 Django 和 LDAP。但是,我想将 LDAP 身份验证限制为仅本地帐户数据库中的帐户。
即,如果没有本地帐户,则拒绝 access/ldap 发生身份验证。
通过查看 LDAPSearch
中的选项,我无法找到提供此功能的直接选项。关于如何实现这一点有什么想法吗?
基于 LDAP OU 的限制不是基于现有 LDAP 地址结构的选项。
谢谢,
如felix001 pointed out in the comments, the project documentation describes a flag 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
模块)。
我目前正在使用 Django 和 LDAP。但是,我想将 LDAP 身份验证限制为仅本地帐户数据库中的帐户。 即,如果没有本地帐户,则拒绝 access/ldap 发生身份验证。
通过查看 LDAPSearch
中的选项,我无法找到提供此功能的直接选项。关于如何实现这一点有什么想法吗?
基于 LDAP OU 的限制不是基于现有 LDAP 地址结构的选项。
谢谢,
如felix001 pointed out in the comments, the project documentation describes a flag 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
模块)。