Search code examples
.netactive-directoryldapldap-queryadsi

LDAP Search Filter Syntax (ONLY) to Identify Objects in a Specific OU (AD)


Many of the non-LDAP-specific applications that interface with AD (e.g. apps that read in objects or use AD for auth) allow only for specifying an LDAP search filter. The problem with this though is that I can't limit the query anything below the default domain partition level (at least, AFAIK).

In an attempt to address this, I was trying search filters like:

(&(objectClass=user)(objectCategory=person)(distinguishedname=*,OU=MyNamedOU,DC=*))

...however, after it didn't work, I started finding articles about how you can't query based on distinguishedname as it's a constructed attribute.

Regardless, is there a way to limit a query to a specific OU based just in the Search Filter syntax alone?

TIA


Solution

  • Active Directory does not allow you to search a partial match on distinguishedName. If distinguishedName is in the query, it can only be an exact match. This is true of any attribute that takes a distinguishedName, like manager, member, etc.

    There really is no way to limit a query to a specific OU by the query string alone, since there is no searchable attribute that has the OU. If you want to search only specific OUs, you will either need to:

    1. Search a single OU by setting the SearchRoot (sometimes called "search base") to that OU rather than the whole domain. You can also set the SearchScope to SearchScope.OneLevel to not search sub-OUs if you want. Repeat the search for every OU you want to include. Or,
    2. Search the top-most OU with the results you want, loop through the results, and discard the ones in the OU's you don't want by looking at the distinguishedName. (since you already have the results at this point, the distinguishedName is just a string you can do whatever you want with, including a partial match)

    The second option will usually be faster since it means one search against AD instead of multiple, but it depends on how many results you end up with and how many you're discarding.