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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3026909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:24:01  来源:igfitidea点击:

Determine if a user belongs to a particular AD Group using .Net

.netactive-directory

提问by rami

What is the best way to determine if a user belongs to particular AD user group using C# without have to enumerate through all the user's groups. Can this be done using a single LDAP query or search?

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

回答by ewall

If you are checking the current user and you know the name of the group you want, you shouldn't need to enumerate through all the groups. Here's example code in VB.NET:

如果您正在检查当前用户并且您知道所需组的名称,则不需要枚举所有组。下面是 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

Similarly in C#:

在 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);
}

More examples can be found in the WindowsIdentity documentation, if you need to tweak it to check a different user's membership or whatever.

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

回答by Cade Roux

I think you do have to enumerate groups.

我认为你必须枚举组。

Have a look at these two answers for a variety of techniques:

看看这两个关于各种技术的答案:

See if user is part of Active Directory group in C# + Asp.net

查看用户是否属于 C# + Asp.net 中的 Active Directory 组

How to write LDAP query to test if user is member of a group?

如何编写 LDAP 查询来测试用户是否是组成员?