C#使用不同的用户凭据访问active directory

C#使用不同的用户凭据访问active directory,c#,.net,active-directory,directoryservices,C#,.net,Active Directory,Directoryservices,我们刚刚为用户提供了一个新的用户创建应用程序。但是,这些用户需要能够通过应用程序创建用户,即使他们自己没有创建用户的权限 在C#中,如何模拟另一个用户以获得此功能。此应用程序主要使用System.DirectoryServices 代码段: DirectoryEntry dEntry = new DirectoryEntry("LDAP://OU="); DirectorySearcher dSearcher = new DirectorySearcher(dEntry); //filter j

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

在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();
您可以直接使用该类并指定用户名和密码:

DirectoryEntry de = new DirectoryEntry(path);

de.Username = "username";
de.Password = "password";
并从de对象访问Active Directory。或者您可以使用
WindowsIdentity
类并模拟用户:

WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle());
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
完整的代码示例可从以下网址获得:

使用


另外,
DirectoryEntry
DirectorySearcher
SearchResultCollection
类型是
IDisposable
-您需要使用
using
语句来处理它们。

使用DirectoryEntry构造函数(字符串、字符串、字符串、身份验证类型)它采用用户名和密码而不是模拟

DirectoryEntry directoryEntry = new DirectoryEntry("IIS://" + serverName + "/W3SVC/1/Root", @"domain\username", "password", AuthenticationTypes.Secure | AuthenticationTypes.Sealing); 

您可以使用特权凭据连接到AD或模仿其他答案所建议的特权用户

但这会带来安全隐患,因为这意味着您的用户可以将这些特权凭证用于其他未经授权的目的


更安全的解决方案是创建一个在具有适当AD权限的服务帐户下运行的web服务。用户可以使用Windows身份验证对web服务进行身份验证,web服务将代表他们创建用户。它可以使用授权来限制允许用户执行的操作(例如,仅在其自己的部门中创建用户)。

是否以管理员身份运行流程/服务?我知道如何手动操作,但我不知道它如何在.NET中自动运行。