有没有办法使用java获取Active Directory中所有组的名称?
答案 0 :(得分:10)
使用Java JNDI,搜索(objectclass = group)并请求cn属性。这将获得所有组名称。
代码示例:
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
public class Test {
public static String ldapUri = "ldap://localhost";
public static String usersContainer = "cn=users,dc=example,dc=com";
public static void main(String args[]) {
if (args.length != 2) {
System.out.println("Usage: test userName password");
return;
}
String username = args[0];
String password = args[1];
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri);
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext ctx = new InitialDirContext(env);
SearchControls ctls = new SearchControls();
String[] attrIDs = { "cn" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration answer = ctx.search(usersContainer, "(objectclass=group)", ctls);
while (answer.hasMore()) {
SearchResult rslt = (SearchResult) answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println(attrs.get("cn"));
}
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:2)
您可以使用此库。它易于使用且功能强大
答案 2 :(得分:0)
我使用Kalyan的示例来查询用户组,但发现尽管查询有效,但它并未返回所有用户组。经过一番挖掘,我开始意识到AD全球目录并基于this example,我能够修改Kalyan的答案,从全局目录中返回所有用户组。
所需的更改是:
3268
将第一个参数设置为Context.search
为""
。
public static void main(String args[]) {
String ldapUri = "ldap://ad.domain.com";
if (args.length != 2) {
System.out.println("Usage: test userName password");
return;
}
String username = args[0];
String password = args[1];
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUri + ":3268");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
DirContext context = new InitialDirContext(env);
SearchControls searchControls = new SearchControls();
String[] attrIDs = {"cn"};
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration answer = context.search("", "(objectclass=group)", searchControls);
while (answer.hasMore()) {
SearchResult rslt = (SearchResult) answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println(attrs.get("cn"));
}
context.close();
} catch (NamingException e) {
e.printStackTrace();
}
}