Home > Back-end >  LDAP search user by attribute in C#
LDAP search user by attribute in C#

Time:11-09

I have a LDAP directory http://btechintegrator.com/index.php/2020/01/22/free-online-cloud-ldap/ where i wanted to find the user with custom attribute.

I have following for getting all users

public List<Dictionary<string, string>> search(string baseDn, string ldapFilter)
        {          

            var result = new List<Dictionary<string, string>>();
            var request = new SearchRequest(baseDn, ldapFilter, SearchScope.Subtree);
            if (request != null)
            {
                var response = (SearchResponse)connection.SendRequest(request);

                foreach (SearchResultEntry entry in response.Entries)
                {
                    var dic = new Dictionary<string, string>();
                    dic["DN"] = entry.DistinguishedName;

                    foreach (string attrName in entry.Attributes.AttributeNames)
                    {
                        //For simplicity, we ignore multi-value attributes
                        dic[attrName] = string.Join(",", entry.Attributes[attrName].GetValues(typeof(string)));
                    }

                    result.Add(dic);
                }
            }
            return result;
        }

and I am calling like

  var searchResult = client.search("ou=users,o=freeguests,dc=btechsample,dc=com", "objectClass=*");

Any idea what change i could do to get user which are having mobile attribute or the user which are having mobile attribute with certain value

CodePudding user response:

You can use the following :

  • mobile=*: get entries having the mobile attribute with any value
  • mobile=0123: get entries having mobile value 0123

Then, to filter entries with both objectClass AND mobile attributes, use the following syntax :

(&(objectClass=*)(mobile=*))

You might want to specify objectClass=User to ensure you get only User entries (though the objectClass filter may not be necessary at all if the mobile attribute is available only for entries having objectClass=User, but I'm not sure of that, ie. whether or not non-User entries can have a mobile attribute).

Also, you can define which attributes you need to read from the search results, for example :

string[] attrs = new string[] { "dn", "uid", "cn", "mobile" };
var request = new SearchRequest(baseDn, ldapFilter, SearchScope.Subtree, attrs);

You can also specify "*" to read all non-operational attributes, and/or " " for operational attributes.

  • Related