在公司 Active Directory 中具有以下组织结构;
- DC=foo,DC=bar,DC=com
- OU=employees
- CN=employee1
- CN=employee2
- OU=interns
- CN=intern1
- CN=intern2
- OU=x
- OU=y
- OU=z
我需要检索单个列表;
employees having attribute "A" and not having attribute "B" and interns having attribute "B" and not having attribute "A".
生成 Spring LDAP 的 LdapContextSource
通过将 DC=foo,DC=bar,DC=com 设置为基础,我在 LdapTemplate
上看不到任何搜索 API用于设置具有单独过滤器的多个搜索库。
这是一个不返回任何匹配项的示例代码;
@Configuration
public class LdapConfiguration {
@Autowired
Environment env;
@Bean
public LdapContextSource contextSource () {
LdapContextSource contextSource= new LdapContextSource();
contextSource.setUrl(env.getRequiredProperty("ldap.url"));
contextSource.setBase("DC=foo,DC=bar,DC=com");
contextSource.setUserDn(env.getRequiredProperty("ldap.user"));
contextSource.setPassword(env.getRequiredProperty("ldap.password"));
return contextSource;
}
@Bean
public LdapTemplate ldapTemplate() {
return new LdapTemplate(contextSource());
}
private List<Contact> ldapsearch(AndFilter filter) {
OrFilter orFilter = new OrFilter();
// EMPLOYEE FILTER
AndFilter employeesFilter = new AndFilter();
employeesFilter.and(filter);
// ou=employees
employeesFilter.and(new EqualsFilter(DirectoryConstants.OU, DirectoryConstants.EMPLOYEES));
// A=*
employeesFilter.and(new PresentFilter(DirectoryConstants.A));
// (!(B=*))
employeesFilter.and(new NotPresentFilter(DirectoryConstants.B));
// INTERN FILTER
AndFilter internFilter = new AndFilter();
internFilter.and(filter);
// ou=interns
internFilter.and(new EqualsFilter(DirectoryConstants.OU, DirectoryConstants.INTERNS));
// (!(A=*))
internFilter.and(new NotPresentFilter(DirectoryConstants.A));
// (B=*)
internFilter.and(new PresentFilter(DirectoryConstants.B));
orFilter.or(employeesFilter);
orFilter.or(internFilter);
List<Contact> contacts = null;
try {
contacts = ldapTemplate().search(
"",
orFilter.encode(),
new AttributesMapper<Contact>() {
public Contact mapFromAttributes(Attributes attrs) throws NamingException {
return buildContact(attrs);
}
});
} catch (Exception e) {
logger.error("Active directory search failed. " + e.getMessage());
}
return contacts;
}
}
我相信过滤器ou=employees
和ou=interns
以上不应是过滤器的一部分,而应是 base
的一部分( ldapTemplate().search()
的第一个参数)。但是我找不到任何 API 既不能将多个基数设置为 ldapTemplate().search()
也不为每个碱基设置单独的过滤器。
关于单步执行此查询有什么想法吗?
最佳答案
您可以使用 LdapQuery.base(DirectoryConstants.EMPLOYEES) 过滤其 OU 为 DirectoryConstants.EMPLOYEES 的项目。下面的代码显示查找 OU 为“dev”且名为 objectClass 的属性为“group”的所有项目。
LdapQuery query = LdapQueryBuilder.query()
.base("ou=dev")
.where("objectClass").is("group");
return ldapTemplate.search(query, new AttributesMapper<String>() {
@Override
public String mapFromAttributes(Attributes attributes) throws NamingException {
return (String) attributes.get("cn").get();
}
});
关于java - Spring LdapTemplate 使用单独的过滤器在多个基础上进行搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37946940/