Bind to LDAP using System.DirectoryServices

Main:

try
{
    // TODO: Add code here to start your service.
    WriteToFile("Auth Test started at " + System.DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
    WriteToFile("====================================");

    #region test 1
    WriteToFile("Test 1: username1 correct password...");
    if (AuthenticateAccount("username1", "secret"))
    {
        WriteToFile("\tBind succeeded");
    }
    else
    {
        WriteToFile("\tBind failed");
    }
    WriteToFile("====================================");
    #endregion
    #region test 2
    WriteToFile("Test 2: username1 incorrect password...");
    if (AuthenticateAccount("username1", "wr0ngp@ssw0rd!"))
    {
        WriteToFile("\tBind succeeded");
    }
    else
    {
        WriteToFile("\tBind failed");
    }
    #endregion

    WriteToFile("====================================");
    WriteToFile("Auth Test finished at " + System.DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss"));
}
catch (Exception e)
{
    WriteToFile("=============EXCEPTION==============");
    WriteToFile("Error: " + e.Message);
    WriteToFile("Error: " + e.StackTrace);
    WriteToFile("Error: " + e.Source);
    WriteToFile("Error: " + e.ToString());
    WriteToFile("=============EXCEPTION==============");
}

Worker Function:

private bool AuthenticateAccount(string username, string password)
{
    try
    {
        System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
        this.WriteToFile("\t\tCurrent Identity = " + identity.Name);
        this.WriteToFile("\t\t\tIsSystem = " + identity.IsSystem);
        this.WriteToFile("\t\t\tIsAuthenticated = " + identity.IsAuthenticated);
        this.WriteToFile("\t\t\tAuthenticationType = " + identity.AuthenticationType);
        this.WriteToFile("\t\t\tToken = " + identity.Token.ToString());

        this.WriteToFile("\t\tConnecting to: " + LDAP_SERVER + ":" + LDAP_PORT + "/" + LDAP_BASEDN);

        using (DirectoryEntry directoryentry = new DirectoryEntry())
        {
            directoryentry.Path = "LDAP://" + LDAP_SERVER + ":" + LDAP_PORT + "/" + LDAP_BASEDN;
            directoryentry.Username = username;
            directoryentry.Password = password;
            directoryentry.AuthenticationType = AuthenticationTypes.Secure;

            try
            {
                this.WriteToFile("\t\t\tCreating Native Object");
                object native_object = directoryentry.NativeObject;
                this.WriteToFile("\t\t\tNativeObject created successfully");
            }
            catch (Exception ex)
            {
                WriteToFile("======= NATIVE OBJ EXCEPTION=======");
                WriteToFile("Error: " + ex.Message);
                WriteToFile("Error: " + ex.StackTrace);
                WriteToFile("Error: " + ex.Source);
                WriteToFile("Error: " + ex.ToString());
                WriteToFile("======= NATIVE OBJ EXCEPTION=======");

                return false;
            }

            directoryentry.Close();
        }

        return true;
    }
    catch(Exception e)
    {
        WriteToFile("========== AUTH EXCEPTION==========");
        WriteToFile("Error: " + e.Message);
        WriteToFile("Error: " + e.StackTrace);
        WriteToFile("Error: " + e.Source);
        WriteToFile("Error: " + e.ToString());
        WriteToFile("========== AUTH EXCEPTION==========");
        return false;
    }
}

Another Example:

    using  System.DirectoryServices.AccountManagement;

    string userDomain = "domain";
    string userName = "username";
    string password = "password";
    string rootDomain = "your.corp.com";
    string rootPath = "LDAP://" + rootDomain;

    string fullUserName = userDomain + "\" + userName;

    // Use PrincipalContext to verify credentials
    PrincipalContext context = new PrincipalContext(ContextType.Domain, rootDomain);
    if (!context.ValidateCredentials(fullUserName, password)) {
        throw new AccessViolationException("Invalid username or password");
    }

    // Find all groups
    DirectoryEntry rootEntry = new DirectoryEntry(rootPath, fullUserName, password);
    DirectorySearcher searcher = new DirectorySearcher(
        rootEntry,"(objectCategory=group)",
        new[] { "cn", "distinguishedName" },SearchScope.Subtree);
    List<string> allGroups = new List<string>(
        from SearchResult result in searcher.FindAll()
        select (string)result.Properties["cn"][0]);

Leave a Reply