Search code examples
active-directoryldap

How to get user by it's objectGUID from Active Directory by using Novell.Directory.Ldap.NETstandard?


I am writing a .NET Core application. The application is using "Novell.Directory.Ldap.NETStandard" v3.6.0 to connect with Active Directory on Windows. I am trying to fetch an entry using objectGUID but there is no base search available which means I need to search in the whole directory. Below is the code sample i am using.

string ldapHost = "ldap.example.com";
int ldapPort = 389;
string ldapUser = "cn=admin,dc=example,dc=com";
string ldapPassword = "password";

string searchBase = ""; // Set to null/empty to search from the root

string[] _attributes = { "objectGUID", "objectCategory", "objectClass" };

// Construct the search filter with the objectGUID attribute and the GUID value
string searchFilter = "(objectGUID=3EBCE0D7-89A1-41A5-9AFD-71C2A8BEC408)";

LdapConnection ldapConnection = new LdapConnection();
ldapConnection.Connect(ldapHost, ldapPort);
ldapConnection.Bind(ldapUser, ldapPassword);

LdapSearchConstraints searchConstraints = new LdapSearchConstraints();
searchConstraints.ReferralFollowing = true;

LdapSearchResults searchResults;
try
{
    searchResults = (LdapSearchResults)ldapConnection.Search(
            searchBase,
                LdapConnection.ScopeSub,
                    searchFilter,
                        _attributes,
                            false,
                                searchConstraints);
}
catch (LdapException ex)
{
    Console.WriteLine("Search operation failed: " + ex.Message);
    ldapConnection.Disconnect();
    return;
}

if (searchResults.HasMore())
{
    LdapEntry entry = searchResults.Next();
    string distinguishedName = entry.Dn;
    Console.WriteLine("Entry Found: " + distinguishedName);
}
else
{
    Console.WriteLine("Entry not found.");
}

ldapConnection.Disconnect();

Please note the searchBase is passed with string.Empty to search in the whole directory. When the code runs the connection establishes fine and gets below exception on searchResults.Next()

'No Such Object'

Please help me to find an entry from an active directory by using objectGUID where no search base is available.

Thanks.


Solution

  • Active Directory allows you to bind directly to an object by the GUID using this format: <GUID=XXXXX>

    So I believe you can set the search base to that and set the search scope to ScopeBase, like this:

    searchResults = (LdapSearchResults)ldapConnection.Search(
            "<GUID=3EBCE0D7-89A1-41A5-9AFD-71C2A8BEC408>",
            LdapConnection.ScopeBase,
            "",
            _attributes,
            false,
            searchConstraints);
    
    

    I've only done this with Microsoft's DirectoryEntry - I have no experience with the Novell library, so this might need some tweaks to get it to work.