Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to provide DirectoryEntry.Exists with credentials?

This morning I discovered a nice method (DirectoryEntry.Exists), that should be able to check whether an Active Directory object exists on the server. So I tried with a simple:

if (DirectoryEntry.Exists(path)) {}

Of course it lacks any overloads to provide credentials with it. Because, if credentials are not provided I get this Exception:

Logon failure: unknown user name or bad password. (System.DirectoryServices.DirectoryServicesCOMException)

Is there any other option that gives me the possibility to authenticate my code at the AD server? Or to check the existence of an object?

like image 800
Herman Cordes Avatar asked Nov 26 '10 10:11

Herman Cordes


3 Answers

In this case you can't use the static method Exists as you said :

DirectoryEntry directoryEntry = new DirectoryEntry(path);
directoryEntry.Username = "username";
directoryEntry.Password = "password";

bool exists = false;
// Validate with Guid
try
{
    var tmp = directoryEntry.Guid;
    exists = true;
}
catch (COMException)
{
   exists = false; 
}
like image 90
JoeBilly Avatar answered Nov 11 '22 02:11

JoeBilly


I know this is an old question, but the source code is now available so you can just Steal and Modify™ to make a version that accepts credentials:

public static bool Exists(string path, string username, string password)
{
    DirectoryEntry entry = new DirectoryEntry(path, username, password);
    try
    {
        _ = entry.NativeObject;       // throws exceptions (possibly can break applications)
        return true;
    }
    catch (System.Runtime.InteropServices.COMException e)
    {
        if (e.ErrorCode == unchecked((int)0x80072030) ||
             e.ErrorCode == unchecked((int)0x80070003) ||   // ERROR_DS_NO_SUCH_OBJECT and path not found (not found in strict sense)
             e.ErrorCode == unchecked((int)0x800708AC))     // Group name could not be found
            return false;
        throw;
    }
    finally
    {
        entry.Dispose();
    }
}

The one change you must make is changing the use of Bind, since that's an internal method and can't be used by mere mortals like us. Instead, I just get the NativeObject property, which calls Bind() for us.

You can use that like this:

var ouExists = Exists("LDAP://hadoop.com/OU=Students,DC=hadoop,DC=com", "username", "password");
like image 37
Gabriel Luci Avatar answered Nov 11 '22 02:11

Gabriel Luci


There is no way to do this and I have written a connect issue to hopefully resolve it.

DirectoryEntry.Exists Does Not Accept Credentials

like image 2
ΩmegaMan Avatar answered Nov 11 '22 03:11

ΩmegaMan