Search code examples
c#active-directoryasp.net-core-webapiwindows-server-2016

DirectoryEntry.Exists runs as CLI but not in WebAPI (dotnet c# activedirectory)


I'm writing an API to check if an OU exists in ActiveDirectory or not. To perform this check, in C#, I run:

string ouName = "MyOrg";
bool ouExists = DirectoryEntry.Exists ($"LDAP://OU={ouName},DC=test,DC=local");

When I create a new CLI project and run these lines, they work fine (the app is running on the DC itself). But when called by a Controller in a WebAPI project, they throw a runtime COMException (80004005), with the details being "Unspecified error".

I figure this has to do with how Kestrel runs the code. It should authenticate automatically as the current loggedonuser (i.e. I can't use the username, password optional parameters).

How do I do that? And is this the right way to go about it?

Exception details:

System.Runtime.InteropServices.COMException (0x80004005): Unspecified error
   at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
   at System.DirectoryServices.DirectoryEntry.Exists(String path)
   at OUCheck.Helpers.ActiveDirectoryHelper.OUExists(String ouDN) in /Projects/OUCheck/Helpers/ActiveDirectoryHelper.cs:line 14
System.Runtime.InteropServices.COMException

Solution

  • The format of the paths for the DirectoryEntry are wrong. I can't find a supporting document, but the following is the difference:

    I was making the queries like this: LDAP://{DN}

    LDAP://OU=MyOrg,DC=test,DC=local
    

    While it seems the correct way to do it is: LDAP://{domain}/{DN}

    LDAP://test.local/OU=MyOrg,DC=test,DC=local
    

    CLI apps work even with the former, perhaps assuming things about the domain.

    The following transcript helped me realize, also thanks to Gabriel for some direction! https://chat.stackoverflow.com/transcript/12432/2012/6/12

    Also might be useful: Get all users from Active Directory?