C# accessing active directory with different user credentials

14,839

You can use the DirectoryEntry class directly and specify the username and password:

DirectoryEntry de = new DirectoryEntry(path);

de.Username = "username";
de.Password = "password";

And access Active Directory from the de object. Or you can use the WindowsIdentity class and and impersonate a User:

WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
WindowsImpersonationContext impersonatedUser = newId.Impersonate();

A full code sample is available at:

Impersonation and DirectoryEntry

Share:
14,839
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin almost 2 years

    There is a new user creation application that we have just provided our users. However these users need the ability to creation users through the application even though they themselves do not have permission to create users.

    In C# how do you impersonate another user in order to have this functionality. This application primary using System.DirectoryServices.

    Code snippet:

    DirectoryEntry dEntry = new DirectoryEntry("LDAP://OU=");
    DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
    //filter just user objects
    dSearcher.SearchScope = SearchScope.Subtree;
    dSearcher.Filter = "(&(objectClass=user)(mail=" + excel_Holding_Table.Rows[i]["EmailAddress"].ToString() + "))";
    dSearcher.PageSize = 1000;
    sResults = dSearcher.FindAll();