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?
+1
A:
I think you do have to enumerate groups.
Have a look at these two answers for a variety of techniques:
Cade Roux
2010-06-11 23:50:48
A:
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)
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)
If MyPrincipal.IsInRole(GroupName) Then
Return True
Else
Return False
End If
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)) ? true : false;
}
More examples can be found in the WindowsIdentity documentation, if you need to tweak it to check a different user's membership or whatever.
ewall
2010-06-12 00:17:07