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

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

在C#中,您如何模拟其他用户才能拥有此function。 此应用程序主要使用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类并指定用户名和密码:

 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

使用带有用户名,密码和authenticationType参数的DirectoryEntry构造函数 。

另外, DirectoryEntry DirectorySearcherSearchResultCollection类型是IDisposable – 您需要处理它们,可能使用using语句。

使用DirectoryEntry构造函数(String,String,String,AuthenticationTypes),它使用用户名和密码而不是模拟。

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

参考

您可以使用特权凭据连接到AD,或者像其他答案所建议的那样模拟特权用户。

但这具有安全隐患,因为这意味着您的用户将能够将这些特权凭据用于其他未经授权的目的。

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