Python 基于Django中的登录用户名获取LDAP组

Python 基于Django中的登录用户名获取LDAP组,python,django,python-2.7,active-directory,openldap,Python,Django,Python 2.7,Active Directory,Openldap,我需要使用Django中的LDAP查询检索用户所在的组列表。用例是:用户填写他的LDAP登录凭据,Django将对他进行身份验证,并将分配他的LDAP组 用户登录工作正常,但我无法使用memberUid=%(用户)s筛选组我正在寻找将用户名作为筛选器参数传递给“groupfilter”属性的正确方法。我用LDAP应用程序浏览器测试了该查询,似乎工作正常 OS:Ubuntu 14.04 x64 Python版本:2.7.6 Django版本:(1,6,11,'最终版',0) RatticWeb

我需要使用Django中的LDAP查询检索用户所在的组列表。用例是:用户填写他的LDAP登录凭据,Django将对他进行身份验证,并将分配他的LDAP组

用户登录工作正常,但我无法使用
memberUid=%(用户)s
筛选组我正在寻找将用户名作为筛选器参数传递给“groupfilter”属性的正确方法。我用LDAP应用程序浏览器测试了该查询,似乎工作正常

  • OS:Ubuntu 14.04 x64
  • Python版本:2.7.6
  • Django版本:(1,6,11,'最终版',0)
RatticWeb LDAP配置 我使用django应用程序通过以下本地配置管理用户密码(另请参阅):

conf/local.cfg

此配置文件由settings.py()读取:

ratticweb/settings.py

日志 现在,我需要过滤传递来自用户登录表单的用户名参数的LDAP组,我尝试使用相同格式的userfilter,但服务器返回以下错误:

[Wed Jan 13 16:51:24.257325 2016] [:error] [pid 11280] 2016-01-13 16:51:24,256 [ERROR] Caught Exception while authenticating myusername
[Wed Jan 13 16:51:24.257438 2016] [:error] [pid 11280] Traceback (most recent call last):
[Wed Jan 13 16:51:24.257478 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py", line 323, in authenticate
[Wed Jan 13 16:51:24.257515 2016] [:error] [pid 11280]     self._get_or_create_user()
[Wed Jan 13 16:51:24.257550 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py", line 539, in _get_or_create_user
[Wed Jan 13 16:51:24.257586 2016] [:error] [pid 11280]     self._mirror_groups()
[Wed Jan 13 16:51:24.257620 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py", line 638, in _mirror_groups
[Wed Jan 13 16:51:24.257697 2016] [:error] [pid 11280]     group_names = self._get_groups().get_group_names()
[Wed Jan 13 16:51:24.257734 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py", line 755, in get_group_names
[Wed Jan 13 16:51:24.257770 2016] [:error] [pid 11280]     group_infos = self._get_group_infos()
[Wed Jan 13 16:51:24.257804 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/backend.py", line 803, in _get_group_infos
[Wed Jan 13 16:51:24.257835 2016] [:error] [pid 11280]     self._group_search)
[Wed Jan 13 16:51:24.257864 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/config.py", line 374, in user_groups
[Wed Jan 13 16:51:24.257893 2016] [:error] [pid 11280]     groups = search.execute(ldap_user.connection)
[Wed Jan 13 16:51:24.257928 2016] [:error] [pid 11280]   File "/usr/local/lib/python2.7/dist-packages/django_auth_ldap/config.py", line 150, in execute
[Wed Jan 13 16:51:24.257957 2016] [:error] [pid 11280]     filterstr = self.filterstr % filterargs
[Wed Jan 13 16:51:24.257990 2016] [:error] [pid 11280] TypeError: format requires a mapping
编辑:错误的原因
LDAPSearch
的构造函数按如下方式填充其属性:

self.base_dn = 'groupbase = ou=Groups,dc=mydomain'
self.scope = ldap.SCOPE_SUBTREE
self.filterstr = '(&(objectClass=posixGroup)(memberUid=%(user)s))'
/usr/local/lib/python2.7/dist-packages/django_auth_ldap/config.py#150


最后,我找到了解决方案:

conf/local.cfg

关键因素是使用groupType
PosixGroupType
,因为对组的查询将由Django Auth LDAP在memberUid参数上进行过滤(请注意
user\u Groups
函数的else部分:

class PosixGroupType(LDAPGroupType):
  """
  An LDAPGroupType subclass that handles groups of class posixGroup.
  """
  def user_groups(self, ldap_user, group_search):
    """
    Searches for any group that is either the user's primary or contains the
    user as a member.
    """
    groups = []

    try:
        user_uid = ldap_user.attrs['uid'][0]

        if 'gidNumber' in ldap_user.attrs:
            user_gid = ldap_user.attrs['gidNumber'][0]
            filterstr = u'(|(gidNumber=%s)(memberUid=%s))' % (
                self.ldap.filter.escape_filter_chars(user_gid),
                self.ldap.filter.escape_filter_chars(user_uid)
            )
        else:
            filterstr = u'(memberUid=%s)' % (
                self.ldap.filter.escape_filter_chars(user_uid),
            )

        search = group_search.search_with_additional_term_string(filterstr)
        groups = search.execute(ldap_user.connection)
    except (KeyError, IndexError):
        pass

    return groups

最后,我找到了解决方案:

conf/local.cfg

关键因素是使用groupType
PosixGroupType
,因为对组的查询将由Django Auth LDAP在memberUid参数上进行过滤(请注意
user\u Groups
函数的else部分:

class PosixGroupType(LDAPGroupType):
  """
  An LDAPGroupType subclass that handles groups of class posixGroup.
  """
  def user_groups(self, ldap_user, group_search):
    """
    Searches for any group that is either the user's primary or contains the
    user as a member.
    """
    groups = []

    try:
        user_uid = ldap_user.attrs['uid'][0]

        if 'gidNumber' in ldap_user.attrs:
            user_gid = ldap_user.attrs['gidNumber'][0]
            filterstr = u'(|(gidNumber=%s)(memberUid=%s))' % (
                self.ldap.filter.escape_filter_chars(user_gid),
                self.ldap.filter.escape_filter_chars(user_uid)
            )
        else:
            filterstr = u'(memberUid=%s)' % (
                self.ldap.filter.escape_filter_chars(user_uid),
            )

        search = group_search.search_with_additional_term_string(filterstr)
        groups = search.execute(ldap_user.connection)
    except (KeyError, IndexError):
        pass

    return groups

此错误由
用户
的右filterargs定义缺少I prsume给出。此()是生成异常的代码行:
filterstr=self.filterstr%filterargs
此错误由
用户
的右filterargs定义缺少I prsume给出。此()生成异常的代码行:
filterstr=self.filterstr%filterargs
def execute(self, connection, filterargs=()):
    """
    Executes the search on the given connection (an LDAPObject). filterargs
    is an object that will be used for expansion of the filter string.

    The python-ldap library returns utf8-encoded strings. For the sake of
    sanity, this method will decode all result strings and return them as
    Unicode.
    """
    try:
        filterstr = self.filterstr % filterargs
        results = connection.search_s(self.base_dn.encode('utf-8'),
                                      self.scope,
                                      filterstr.encode('utf-8'))
    except ldap.LDAPError, e:
        results = []
        logger.error(u"search_s('%s', %d, '%s') raised %s" %
                     (self.base_dn, self.scope, filterstr, pprint.pformat(e)))

    return self._process_results(results)
[ldap]
....
# Set up the basic group parameters.
groupbase = ou=Groups,dc=mydomain
groupfilter = (objectClass=posixGroup)  
grouptype = PosixGroupType
...
class PosixGroupType(LDAPGroupType):
  """
  An LDAPGroupType subclass that handles groups of class posixGroup.
  """
  def user_groups(self, ldap_user, group_search):
    """
    Searches for any group that is either the user's primary or contains the
    user as a member.
    """
    groups = []

    try:
        user_uid = ldap_user.attrs['uid'][0]

        if 'gidNumber' in ldap_user.attrs:
            user_gid = ldap_user.attrs['gidNumber'][0]
            filterstr = u'(|(gidNumber=%s)(memberUid=%s))' % (
                self.ldap.filter.escape_filter_chars(user_gid),
                self.ldap.filter.escape_filter_chars(user_uid)
            )
        else:
            filterstr = u'(memberUid=%s)' % (
                self.ldap.filter.escape_filter_chars(user_uid),
            )

        search = group_search.search_with_additional_term_string(filterstr)
        groups = search.execute(ldap_user.connection)
    except (KeyError, IndexError):
        pass

    return groups