LDAP 过滤器语法

LDAP Filter Syntax

我正在使用 python 库 ldap3 向服务器发送请求,以查询未禁用且具有包含用户输入的显示名称或电子邮件的用户对象:

query = "(&(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(displayName={0}*)(mail={0}*))".format(value)

我按照我认为 documentation 所说的关于形成 LDAP 过滤器的内容进行了操作,但我收到了不正确的 LDAP 过滤器错误消息:

LDAPInvalidFilterError: malformed filter

我试了一下,效果不错:

query = "(&(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(displayName={0}*))".format(value) 

我还不能使用 | 构建过滤器。应该如何构造查询?

您不能简单地将任何值 .format() 放入过滤器中。

在将它们插入字符串之前,您需要 escape certain characters

*     -> a
(     -> 
)     -> 
\     -> c
NUL   -> [=14=]
/     -> f

就像 URL 一样,您可以使用上述方案自由转义 任何您喜欢的 字符,但以上是最少的字符。

I haven't been able to construct a filter using | yet. How should the query be constructed?

也就是说,你有一个嵌套错误。您会在设置查询格式时看到它:

(&
  (objectClass=user)
  (!(userAccountControl:1.2.840.113556.1.4.803:=2))
  (|
    (displayName={0}*)
    (mail={0}*)
  )

您仍然需要转义 value,但由于 LDAP 服务器不关心,请保持查询格式:

value = ldap3.utils.conv.escape_filter_chars(user_input)
query = f"""
(&
  (objectClass=user)
  (!(userAccountControl:1.2.840.113556.1.4.803:=2))
  (|
    (displayName={value}*)
    (mail={value}*)
  )
)
"""