C# 使用不同的用户凭据访问活动目录
- 作者: 特别靠谱先生
- 来源: 51数据库
- 2022-10-21
问题描述
我们刚刚为用户提供了一个新的用户创建应用程序.然而,这些用户需要能够通过应用程序创建用户,即使他们自己没有创建用户的权限.
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.
在 C# 中,您如何模拟其他用户以获得此功能.此应用程序主要使用 System.DirectoryServices.
In C# how do you impersonate another user in order to have this functionality. This application primary using 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 类直接指定用户名和密码:
You can use the DirectoryEntry class directly and specify the username and password:
DirectoryEntry de = new DirectoryEntry(path); de.Username = "username"; de.Password = "password";
并从 de 对象访问 Active Directory.或者您可以使用 WindowsIdentity 类并模拟用户:
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();
完整代码示例位于:
模拟和目录条目
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
