Get list of LDAP domain user names using Java

Kumar picture Kumar · Dec 13, 2011 · Viewed 11k times · Source

The ldap user names need to be displayed in the the input box as autocomplete feature. I am trying to get list of users as below:

        String ldapURL = "ldap://192.26.75.5:389/dc=northamerica,dc=company,dc=com";
    String principalPrefix = "domainName";      
    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    String password = SecurityContextHolder.getContext().getAuthentication().getCredentials().toString();

    Hashtable<String, String>environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL,ldapURL);
    environment.put(Context.SECURITY_AUTHENTICATION,"simple");
    environment.put(Context.SECURITY_PRINCIPAL,principalPrefix + "\\" + username);
    environment.put(Context.SECURITY_CREDENTIALS,password);
    environment.put( Context.REFERRAL, "follow" );

    DirContext context = null;
    NamingEnumeration<SearchResult> enumResult = null;      
    try
    {
                    context = new InitialDirContext(environment);                       
                    SearchControls controls = new SearchControls();                     
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    String[] attrIDs ={"ou","uid", "givenname", "sn", "mail"};
                    controls.setReturningAttributes(attrIDs);
                    enumResult = context.search("","(&(objectCategory=person)(objectClass=user)(CN=*))", controls);                     
                    if(enumResult != null)
                    {
                                    //authentication successful                                 
                    }                       
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }

However "enumResult" always gets single user value. Let me know if i am missing out something or if its the wrong way to do it. Any help/advice/suggestion would be appreciated !! Thanks.

Answer