如何使用Spring查找LDAP中同CN前缀的所有组?
用Spring LDAP通配符查询匹配CN前缀的所有组
lookupContext方法仅能查询单个指定DN的条目,要实现通配符批量搜索,你需要使用LdapTemplate的search方法,结合LDAP过滤语法来匹配目标组。
实现步骤
- 确定搜索基础DN:以
OU=developerGroups,DC=mycomp,DC=com作为搜索根节点,限定搜索范围在该组织单元下。 - 构建过滤条件:用LDAP过滤语法匹配CN以
developer.开头的条目,基础过滤规则为(cn=developer.*)。如果需要仅搜索组对象(避免匹配其他类型条目),可添加对象类限制,过滤规则改为(& (objectClass=group) (cn=developer.*))。 - 执行搜索并处理结果:通过
search方法执行查询,按需提取条目属性。
代码示例
方式1:获取完整的组条目(DirContextOperations)
String baseDn = "ou=developerGroups,dc=mycomp,dc=com"; // 过滤条件:匹配CN以developer.开头的组 String filter = "(& (objectClass=group) (cn=developer.*))"; List<DirContextOperations> groupEntries = ldapTemplate.search( baseDn, filter, (AttributesMapper<DirContextOperations>) attributes -> { DirContextAdapter context = new DirContextAdapter(attributes); // 设置条目DN(可选,若后续需要完整DN) String cn = attributes.get("cn").get().toString(); context.setDn(LdapUtils.newLdapName(String.format("cn=%s,%s", cn, baseDn))); return context; } ); // 遍历处理结果 for (DirContextOperations group : groupEntries) { String groupCn = group.getStringAttribute("cn"); String groupDn = group.getDn().toString(); // 这里添加你的业务处理逻辑 System.out.printf("找到组:%s,DN:%s%n", groupCn, groupDn); }
方式2:仅提取组的CN属性
如果只需要组的通用名称,可以简化结果映射:
String baseDn = "ou=developerGroups,dc=mycomp,dc=com"; String filter = "(& (objectClass=group) (cn=developer.*))"; List<String> groupCns = ldapTemplate.search( baseDn, filter, (AttributesMapper<String>) attributes -> attributes.get("cn").get().toString() ); // 输出所有匹配的组CN groupCns.forEach(cn -> System.out.println("匹配的组CN:" + cn));
注意事项
- LDAP过滤语法中,
*是通配符,匹配任意长度的字符(包括空字符),developer.*会匹配所有以developer.开头的CN。 - 如果目标LDAP服务器的组对象类不是
group,需要替换为实际的对象类(比如groupOfNames、groupOfUniqueNames等),确保过滤条件准确。
内容的提问来源于stack exchange,提问作者Shivayan Mukherjee
相关产品推荐
相关产品推荐

