首先感谢 Sotirios Delimanolis,他帮助我解决了我的第一个问题(第一部分是访问活动目录)。
所以现在我的代码是:
DirContext ctx = null;
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://"+serverAddress+":389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, DOMAIN+username);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create the initial context
ctx = new InitialDirContext(env);
Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
matchAttrs.put(new BasicAttribute("mail", "XXXXXX@XXXX.com"));
matchAttrs.put(new BasicAttribute("cn"));
// Search for objects that have those matching attributes
NamingEnumeration<SearchResult> answer = ctx.search("ou=People", matchAttrs);
while (answer.hasMore()) {
SearchResult sr = (SearchResult)answer.next();
System.out.println(">>>" + sr.getName());
}
我有错误:
Failed to bind to LDAP / get account information: javax.naming.NamingException: [LDAP: error code 1 - 000020D6: SvcErr: DSID-03100754, problem 5012 (DIR_ERROR), data 0 ; remaining name 'ou=People'
我在http://docs.oracle.com/javase/jndi/tutorial/basics/directory/basicsearch.html找到了这段代码(如下):
// Specify the attributes to match
// Ask for objects that has a surname ("sn") attribute with
// the value "Geisel" and the "mail" attribute
Attributes matchAttrs = new BasicAttributes(true); // ignore attribute name case
matchAttrs.put(new BasicAttribute("sn", "Geisel"));
matchAttrs.put(new BasicAttribute("mail"));
// Search for objects that have those matching attributes
NamingEnumeration answer = ctx.search("ou=People", matchAttrs);
You can then print the results as follows.
while (answer.hasMore()) {
SearchResult sr = (SearchResult)answer.next();
System.out.println(">>>" + sr.getName());
printAttrs(sr.getAttributes());
}
所以我想知道他的目标上下文“ou = People”是否特定于每个活动目录,或者对于“ou”和“People”来说总是相同的:http://www.kouti.com/tables/userattributes。 htm
非常感谢 !