使用.Net确定用户是否属于特定的AD组

15

如何使用C#确定用户是否属于特定的AD用户组,而无需枚举用户的所有组?能否使用单个LDAP查询或搜索来完成此操作?


2个回答

34

如果您正在检查当前用户并且知道您想要的组的名称,那么您不需要枚举所有组。以下是VB.NET的示例代码:

Public Function IsInGroup(ByVal GroupName As String) As Boolean
    Dim MyIdentity As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
    Dim MyPrincipal As System.Security.Principal.WindowsPrincipal = New System.Security.Principal.WindowsPrincipal(MyIdentity)
    Return MyPrincipal.IsInRole(GroupName)
End Function

同样地,在C#中:

private static bool IsInGroup(string GroupName)
{
    System.Security.Principal.WindowsIdentity MyIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
    System.Security.Principal.WindowsPrincipal MyPrincipal = new System.Security.Principal.WindowsPrincipal(MyIdentity);
    return MyPrincipal.IsInRole(GroupName);
}

如果你需要调整以检查不同用户的成员资格或其他内容,可以在WindowsIdentity文档中找到更多示例。


2
这对我非常有帮助。如果您需要检查不同用户的成员身份,只需执行以下操作:var userPrincipal = new WindowsPrincipal(new WindowsIdentity(username)); - Evan M
1
这个可行,但你将无法获取用户所属的所有组的信息,只能获取其中一些。 为了获得用户所属的所有组的完整列表,请查看此答案: (https://dev59.com/Cm435IYBdhLWcg3wuikn) - Roboblob
有趣。谢谢,@Roboblob! - ewall
2
在我的环境中,有1300多个组,IsInRole() 比 GetAuthorizationGroups() 快几个数量级 -- 后者需要几秒钟才能完成。当 IsInRole() 返回负值时,我仍然使用 GetAuthorizationGroups() 作为备用方法来测试间接组成员身份。谢谢! - adipy

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接