How can I get specific user groups using Active Directory? I get all the groups, but I want to get the groups the user is a member of
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;
}
user5585864
source
share