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