Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 559
rami Avatar asked Jun 11 '10 23:06

rami


People also ask

How do you check if a user belongs to an ad group?

You can check group membership with the Active Directory Users and Computers (ADUC) console snap-in by finding the user or group of interest and drilling down into the object's properties and clicking the “Members” or “Member Of” tab.

How do you check which groups a user is in Windows?

In the properties window for the user account, switch to the “Member Of” tab. This tab shows you the local groups to which the user account belongs, and also lets you add the account to other groups.

How do I find the ad group for a user in SQL Server?

To get more database specific information you can go to the database you are interested in and use sys. user_token to get a list of roles/AD groups associated with that database. In this case principal_id is associated with sys. database_principals .


2 Answers

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.

like image 144
ewall Avatar answered Oct 04 '22 12:10

ewall


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?

like image 30
Cade Roux Avatar answered Oct 04 '22 13:10

Cade Roux