C#使用不同的用户凭据访问活动目录

6 .net c# directoryservices active-directory

我们刚刚为用户提供了一个新的用户创建应用程序.但是,这些用户需要能够通过应用程序创建用户,即使他们自己没有创建用户的权限.

在C#中,您如何模拟其他用户才能拥有此功能.此应用程序主要使用System.DirectoryServices.

代码段:

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();
Run Code Online (Sandbox Code Playgroud)

Dar*_*ren 9

您可以DirectoryEntry直接使用该类并指定用户名和密码:

DirectoryEntry de = new DirectoryEntry(path);

de.Username = "username";
de.Password = "password";
Run Code Online (Sandbox Code Playgroud)

并从de对象访问Active Directory.或者您可以使用WindowsIdentity该类并模拟用户:

WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
Run Code Online (Sandbox Code Playgroud)

完整的代码示例可在以下位置获得:

模拟和DirectoryEntry