Search code examples
javaactive-directoryldapldap-query

Find user's member of groups in Microsoft AD inside Domain Users security group


I need to find the member of groups of a given user in Microsoft active directory using java inside the Domain Users group. My AD structure is below.

reg1.subdomain.domain.com -Users (Type - Container) - Domain Users (Type - Security Group Global)

I wrote the below code. But I was unable to query the users inside Domain Users group.

public static String ldapUri = "ldap://ldapuri.com:389";
    public static String usersContainer = "CN=users,DC=reg1,DC=subdomain,DC=domain,DC=com";
    public ArrayList<String> getUserGroups(String username, String password){
        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 = { "memberOf" };
            ctls.setReturningAttributes(attrIDs);
            ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);

            NamingEnumeration answer = ctx.search(usersContainer, "(&(objectCategory=group)(cn=Domain Users)(sAMAccountName=username))", ctls);
            while (answer.hasMore()) {
                SearchResult rslt = (SearchResult) answer.next();
                Attributes attrs = rslt.getAttributes();
                try{
                    String groups = attrs.get("memberOf").toString();
                    String [] groupname = groups.split(":");
                    System.out.println(groupname[1]);
                }catch (Exception e){
                    System.out.println("no members");
                }
            }
            ctx.close();
        } catch (NamingException e) {
            e.printStackTrace();
        }
        return list;
    }

Can someone please point out what's wrong with the filter query I have added?


Solution

  • the given code snippet above is correct except the searching method that I have specified. I was not able to search the users inside Domain Users group from Users container because I have not mentioned to search in sub directories. By adding search scope to,

    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    

    it was able to successfully retrieve the users