如何使用Active Directory获取特定用户组? 我正在获取所有组,但我想获得用户所属的组
public static String ldapUri = "ldap://pdc.example.com:389";
public static String usersContainer = "cn=users,dc=example,dc=com";
public ArrayList<String> getUserGroups(String email, String password){
ArrayList<String> list = new ArrayList<String>();
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, email);
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();
String groups = attrs.get("cn").toString();
String [] groupname = groups.split(":");
String userGroup = groupname[1];
System.out.println(attrs.get("cn"));
}
ctx.close();
} catch (NamingException e) {
e.printStackTrace();
}
return list;
}
答案 0 :(得分:5)
我使用此
获取用户的所有组String[] attrIDs = {"cn"};
ctls.setReturningAttributes(attrIDs);
String[] attributes = {"memberOf"};
ctls.setReturningAttributes(attributes);
NamingEnumeration<?> answer = ctx.search(usersContainer, "(&(objectclass=user)(sAMAccountName=userName))", ctls);
答案 1 :(得分:2)
如果您使用的是Active Directory。 用户具有属性'memberOf';触发特定用户的搜索查询,并在返回属性中包含“memberOf”。
String[] attrIDs = { "cn", "memberOf" };
ctls.setReturningAttributes(attrIDs);
ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
NamingEnumeration answer = ctx.search(usersContainer, "(&(objectclass=person)(cn=*sahi*))", ctls);
'memberOf'属性包含用户所属的组。