views:

27

answers:

2

I want to run this function, or at least the bit that deletes the machine account from AD with different credentials:

 public static void DeleteMachineAccount(String MachineName)
        {
            String MachineLdapPath = LdapPath(MachineName);
            String OuLdapPath = MachineLdapPath.Replace("CN=" + MachineName + ",", "");

            Console.WriteLine(MachineLdapPath);
            Console.WriteLine(OuLdapPath);

            if (DirectoryEntry.Exists(MachineLdapPath))
            {
                try
                {
                    DirectoryEntry MachineOu = new DirectoryEntry(OuLdapPath);
                    DirectoryEntry MachineToDelete = new DirectoryEntry(MachineLdapPath);
                    MachineOu.Children.Remove(MachineToDelete);
                    MachineToDelete.CommitChanges();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message.ToString());
                }
            }

        }

(The LdapPath function just returns an LDAP path for the machine name specified.)

How / where do I specify some different credentials to allow this to run? At the moment I get access denied, as the account I am using will not have permission to do this.

Thanks,

Ben

A: 

You need to use impersonation. The easiest way to do this is to actually "borrow" the permission of whoever called this method. e.g., if this is invoked from a named pipe or WCF call, there are built-in ways to impersonate the caller and do this on their behalf.

Stephen Cleary
+1  A: 

You can use the overload of the DirectoryEntry class that provides authentication. This will cause your LDAP query to be run from the DirectoryServices with this particular user's permission. A word of caution, in order to do this you'll need to pass credentials (which would need to be stored or entered by the user), so be careful in how you handle them. Storing them in plain text may cause system security problems.

New DirectoryEntry(ldapRoot, _activeDirectoryUsername, _activeDirectoryPassword);
Joel Etherton