Skip to main content
 首页 » 编程设计

python之使用 LDAP 和本地帐户的 Django 身份验证

2024年09月03日33thcjp

我目前正在使用 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 模块)。