Search code examples
javaldapou

How to get all users from specific ou in active directory using java?


Here is the method which i have used to fetch but nothing is being populated.

public void doSearch() throws NamingException {
        String searchFilter = "(&(ou=Example,ou=Examples_ou)(objectClass=person))";
        String domain = "DC=mydom,DC=com";
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration<SearchResult> answer = ctx.search(domain, searchFilter, searchControls);
        int ttl = 0;
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            ttl++;
            System.out.println(">>>" + sr.getName());
            Attributes attrs = sr.getAttributes();
            System.out.println(">>>>>>" + attrs.get("samAccountName"));
        }
        System.out.println("Total results: " + ttl);
    }

Solution

  • Your filter is invalid, thus returns no data. In

    ctx.search(domain, searchFilter, searchControls);
    

    domain is being passed as the base DN for the search. If you want to restrict your search to users within ou=Example,ou=Examples_ou of dc=example,dc=com, then your search base DN should be "ou=Example,ou=Examples_ou,dc=example,dc=com" and searchFilter would be simply "(&(objectClass=person))"