Determine if a user belongs to a particular AD Group using .Net
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?
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:
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#:
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.
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
How to write LDAP query to test if user is member of a group?
精彩评论