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

ram*_*ami 14 .net active-directory

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

ewa*_*all 33

如果您正在检查当前用户并且您知道所需组的名称,则不需要枚举所有组.这是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
Run Code Online (Sandbox Code Playgroud)

同样在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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这对我非常有帮助.如果您需要检查其他用户的成员身份,请执行以下操作:var userPrincipal = new WindowsPrincipal(new WindowsIdentity(username)); (2认同)
  • 在拥有1300多个组的环境中,IsInRole()比GetAuthorizationGroups()快几个数量级 - 这需要几秒钟才能完成.当IsInRole()为负数时,我仍然使用GetAuthorizationGroups()作为备份来测试间接组成员身份.谢谢! (2认同)