'Find by memberOf=CN=GroupName if the OU= is unknown

I need to find members of certain AD groups, but I only know the group CNs, not their distinguished Names. How to achieve this in java?

I currently pass the following filter to my search function and it returns some results:

(memberOf=CN=VPN_external,OU=VPNGroups,OU=Groups,DC=acme,DC=com)

How do I omit at least OU=VPNGroups because there are groups with other OU?

My search function:

public static NamingEnumeration<SearchResult> search(final String filter)
                                                                           throws NamingException,
                                                                               IOException {
    final LdapContext ctx = connection();
    final SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(attributes);
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    final int pageSize = 100;
    final boolean criticality = true;
    ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, criticality) });

    final String basein = "OU=RealUsers,DC=acme,DC=com";
    return ctx.search(basein, filter, searchCtls);

}

private static LdapContext connection() throws NamingException, IOException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://192.168.1.1");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    final Object username = "joe";
    env.put(Context.SECURITY_PRINCIPAL, username);
    final Object password = "s3cret";
    env.put(Context.SECURITY_CREDENTIALS, password);
    return new InitialLdapContext(
        env,
        new Control[] { new PagedResultsControl(1000, Control.CRITICAL) });
}

private static final String ACTIVE_DIRECTORY_DISPLAYNAME = "displayName";

private static final String ACTIVE_DIRECTORY_SAMACCOUNTNAME = "sAMAccountName";

private static final String ACTIVE_DIRECTORY_MAIL = "mail";

private static final String ACTIVE_DIRECTORY_GIVENNAME = "givenName";

private static final String ACTIVE_DIRECTORY_JOBTITLE = "title";

private static final String ACTIVE_DIRECTORY_ACCOUNTEXPIRES = "accountExpires";

private static final String[] attributes =
    new String[] {
        ACTIVE_DIRECTORY_SAMACCOUNTNAME,
        ACTIVE_DIRECTORY_MAIL,
        ACTIVE_DIRECTORY_DISPLAYNAME,
        ACTIVE_DIRECTORY_GIVENNAME,
        ACTIVE_DIRECTORY_JOBTITLE,
        ACTIVE_DIRECTORY_ACCOUNTEXPIRES };


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source