gpt4 book ai didi

c# - 在 C# 中确定给定 LDAP 服务器详细信息的用户组/声明

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:43 25 4
gpt4 key购买 nike

我们有一个测试事件目录 LDAP 服务器。我还有一些用户名和密码。我想确定特定用户的声明/用户组,同时登录到另一个域。这可以用一些 C# 代码来完成吗?我想我将不得不使用 System.DirectoryServices.dll

最佳答案

如果您可以使用 .Net 3.5 或更高版本,请尝试 System.DirectoryServices.AccountManagement.dll 程序集。它提供了System.DirectoryServices.AccountManagement命名空间和基于主体的类,例如 UserPrincipal 和 GroupPrincipal。它们代表了更高层次的抽象并且更易于使用。

例如,要连接到另一个域中的 LDAP 服务器(根据此抽象获取 Principal Context),您需要使用 this constructor 创建 PrincipalContext 类的实例。 :

PrincipalContext anotherDomainContext = new PrincipalContext(ContextType.Domain, DomainDnsName, RootOU, ContextOptions.SimpleBind, QueryUserName, QueryUserPassword);

RootOU 类似于“DC=Company,DC=COM”,因此 DomainDnsName 类似于“company.com”或“ldapserver.company.com”。如果您的 AD 林中有多个域,请尝试连接到全局目录 (DomainDnsName = "ldapserver.company.com:3268")。 QueryUserName 和 QueryUserPassword 是带有用户名和密码的纯字符串,用于连接到 LDAP 服务器。用户名可以包含域名,例如:

string QueryUserName = @"company\username";

连接到 LDAP 服务器后,您可以搜索用户:

 UserPrincipal user = UserPrincipal.FindByIdentity(anotherDomainContext , IdentityType.SamAccountName, samAccountName);

您在其中提供 samAccountName 和上下文(连接)。

通过手头的 UserPrincipal 实例,您可以访问 its properties and methods .例如,获取用户的安全组:

PrincipalSearchResult<Principal> searchResults = user.GetGroups();
List<GroupPrincipal> groupsList = searchResults.Select(result => result as GroupPrincipal).
Where(group => (group != null) &&
(group.IsSecurityGroup.HasValue) &&
(group.IsSecurityGroup.Value))

请注意,GetGroups 仅返回用户直接所属的组。要获取包括嵌套在内的所有用户组,请调用 GetAuthorizationGroups。此外,您可以避免使用 LINQ,它只是用于从 GetGroups 中过滤安全组。

GroupPrincipal您可以检查名称属性或成员集合。

关于c# - 在 C# 中确定给定 LDAP 服务器详细信息的用户组/声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29508681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com