Java Active Directory查询返回不完整的用户列表

时间:2015-10-30 20:08:09

标签: java active-directory

我想用Java列出所有AD用户。我正在使用此代码:

String ldapUri = "ldap://" + serverName;
LdapContext ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
//it can be <domain\\userid> something that you use for windows login
//it can also be
env.put(Context.SECURITY_PRINCIPAL, adminName);
try {
    env.put(Context.SECURITY_CREDENTIALS, adminPass.getBytes("UTF8"));
    env.put(Context.REFERRAL, "follow");
} catch (java.io.UnsupportedEncodingException e) {
    log.error("Non-Fatal exception : ", e);
    /* ignore */
}
//in following property we specify ldap protocol and connection url.
//generally the port is 389
env.put(Context.PROVIDER_URL, ldapUri);

log.info("AD Server: " + ldapUri + ", admin " + adminName);

ctx = new InitialLdapContext(env, null);

DirContext ctx1 = new InitialDirContext(env);
SearchControls ctls = new SearchControls();
String[] attrIDs = {"distinguishedName", "cn", "name", "uid",
    "sn",
    "name",
    "memberOf",
    "displayName",
    "userPrincipalName"};

ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration answer = ctx1.search(searchPath, "(&(objectClass=user)(objectCategory=person))", ctls);
while (answer.hasMoreElements()) {
    // Process user
    SearchResult rslt = (SearchResult) answer.next();
}

代码在大多数环境中都能正常运行,但有一位客户报告说有些用户丢失了。我尝试对其进行故障排除,但未列出用户,但使用Active Directory管理员或Active Directory资源管理器列出了这些用户。

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

I assume that account you are using has enough permissions. As far as I recall any instance of domain controller will return 1000 objects by default. It is very likely you are running into this situation. You have to use LDAP pagination In order to solve this problem. Take a look into JNDI page controls - https://docs.oracle.com/javase/tutorial/jndi/newstuff/paged-results.html.

Also, take a look into JNDI code samples from Java forum - https://community.oracle.com/thread/1157644?tstart=0.

Hope this helps.

答案 1 :(得分:0)

除了确保没有达到任何查询限制之外,您还应该考虑一些客户可能运行更复杂的Active Directory设置。 这可能涉及多个域。为了解决那些需要连接到全局编录的问题。您可以通过绑定到端口3268来实现此目的。

您应该将此作为标准连接方式,或者由客户站点的管理员进行配置。

在Microsoft了解更多相关信息:https://technet.microsoft.com/de-de/library/cc978012.aspx