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

时间:2010-06-11 23:44:09

标签: .net active-directory

使用C#确定用户是否属于特定AD用户组的最佳方法是什么,而不必枚举所有用户的组。可以使用单个LDAP查询或搜索来完成吗?

2 个答案:

答案 0 :(得分:32)

如果您正在检查当前用户并且您知道所需组的名称,则不需要枚举所有组。这是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 documentation中找到更多示例。

答案 1 :(得分:1)

相关问题