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?
Asked
Active
Viewed 3.9k times
15
-
possible duplicate of [See if user is part of Active Directory group in C# + Asp.net](http://stackoverflow.com/questions/2188954/see-if-user-is-part-of-active-directory-group-in-c-asp-net) – Cade Roux Jun 11 '10 at 23:49
-
possible duplicate of [How to write LDAP query to test if user is member of a group?](http://stackoverflow.com/questions/1032351/how-to-write-ldap-query-to-test-if-user-is-member-of-a-group) – marc_s Jun 12 '10 at 07:18
2 Answers
34
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.
-
2This was tremendously helpful to me. If you need to check a different user's membership just do this: var userPrincipal = new WindowsPrincipal(new WindowsIdentity(username)); – Evan M May 29 '12 at 16:48
-
1This works but you will not get information for all groups, just some of them. In order to get a full list of groups that user is member of, check this answer: (http://stackoverflow.com/questions/5252108/query-from-ldap-for-user-groups) – Roboblob Mar 25 '13 at 13:05
-
-
2In my environment with 1300+ groups, IsInRole() is orders of magnitude faster than GetAuthorizationGroups() -- which takes several seconds to complete. I'm still using GetAuthorizationGroups() as a backup to test for indirect group membership when IsInRole() is negative. Thanks! – adipy Feb 10 '15 at 19:31
2
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?