0

I am trying to automate a powershell process that is used to fetch the users of a specific AD user group.

Here is the powershell command Get-ADGroup Active Directory Group Name -Server ford.com -Properties *).member

This command works fine, but I want the same process to be simulated in Java.

I am trying to try the same process of fetching list of all users under a given AD group. I have tried multiple suggestions in Stack overflow but nothing worked, below is one such sample code I have, but this code is not returning any results.

/**
 * 
 */
package com.mycompany.audit.api.test;


import java.util.Enumeration;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class GetUsersFrormLDAPGroup {
    
    static String groupName="Active Directoty Group Name";
    static String username = "userId@mycompany.com";
    static String password = "Password";
    static String ldapUrl = "ldaps://fds.mycompany.com:636";
     // Initialize
    static LdapContext ldapContext = null;
    static NamingEnumeration<SearchResult> results = null;
    static NamingEnumeration<?> members = null;
    public static void main(String[] args) throws Exception {
    

        try {
            // Initialize properties
            Properties properties = new Properties();
            properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            properties.put(Context.PROVIDER_URL, ldapUrl);
            properties.put(Context.SECURITY_PRINCIPAL, username);
            properties.put(Context.SECURITY_CREDENTIALS, password);

            // Initialize ldap context
            ldapContext = new InitialLdapContext(properties, null);

            String userdn = "OU=Admin,OU=Groups,DC=US,DC=mycompany,DC=com";
            
            SearchControls searchCtrls = new SearchControls();
            searchCtrls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String[] attributes = {"member","memberof"};
            searchCtrls.setReturningAttributes(attributes);
            
            //Change the NameOfGroup for the group name you would like to retrieve the members of.
            String filter = "(&(objectCategory=group)(cn=Active Directory Group Name))";

            //use the context we created above and the filter to return all members of a group.
            NamingEnumeration values = ldapContext.search( userdn, filter, searchCtrls);

            //Loop through the search results
            while (values.hasMoreElements()) {
                System.out.println("Inside while");
                SearchResult sr = (SearchResult)values.next();
                System.out.println(">>>" + sr.getName());
                Attributes attrs = sr.getAttributes();

                if (null != attrs)
                {
                    for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();)
                    {
                        Attribute atr = (Attribute) ae.next();
                        String attributeID = atr.getID();
                        Enumeration vals = atr.getAll();                    

                        if (vals.hasMoreElements()) {
                            String username = (String) vals.nextElement();
                            System.out.println("username");

                        } else {
                            System.out.println("no");
                        }
                    }
                }
            }

        } catch (NamingException e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } finally {
            if (ldapContext != null) {
                ldapContext.close();
            }
            if (results != null) {
                results.close();
            }
        }
    }
        
    /**
     * 
     * @param i
     * @return
     */
    public static String[] generateRangeArray(int i) {
        String range = "member;range=" + i * 1500 + "-" + ((i + 1) * 1500 - 1);
        String[] returnedAtts = { range };
        return returnedAtts;
    }

    /**
     * 
     * @param i
     * @return
     */
    public static String generateRangeString(int i) {
        String range = "member;range=" + i * 1500 + "-" + ((i + 1) * 1500 - 1);
        return range;
    }
}

Can someone let me know what am I missing in the above query or help me out with some sample working code to fetch all users of a AD group.

Karthik P
  • 107
  • 2
  • 12
  • Where did you get that example from? It's not looking at the `member` attribute at all. – Gabriel Luci Dec 20 '21 at 16:22
  • You might have special character to escape from the group name in the search filter (see [How should I escape ldap special characters?](https://stackoverflow.com/a/39805523/2529954)). @GabrielLuci it seems the query retrieves a specific group entry and fetch the 'member' attribute. – EricLavault Dec 20 '21 at 18:44
  • @EricLavault Oh, I didn't see that `attributes` array. I was looking inside the loop for the `member` and didn't see it. – Gabriel Luci Dec 21 '21 at 01:19
  • @EricLavault, thanks for your response, my group names is something like this "ABC-JENKINS-ADMINS" and from the link I see hyphen(-) is an acceptable character. – Karthik P Dec 21 '21 at 06:55
  • If you have some working snippet, please help me with it – Karthik P Dec 21 '21 at 06:56
  • I believe the issue is with `String userdn = "OU=Admin,OU=Groups,DC=US,DC=mycompany,DC=com`, as I am getting PartialResultException as below `javax.naming.PartialResultException: [LDAP: error code 10 - 0000202B: RefErr: DSID-031007F9, data 0, 1 access points` I tried multiple combinations but nothing worked either I am getting PartialResultException or NameNotFound Exception – Karthik P Dec 21 '21 at 07:33

0 Answers0