Check if the windows user exists of one of the AD groups(ADgroup1, AD group2,ADgroup3 etc)

777 views Asked by At

I currently have the code to check if the user is part of a single AD group but how do I check if this user is part of Multiple AD groups. Below is the code I have to check a single group

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

        // find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, Environment.UserName);

        // find the group in question
        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "ADGROUP1");

        if (user != null)
        {
            if (user.IsMemberOf(group))
            {
                //Enable certain Form Buttons and objects for IT Users
                authTbox.Visible = true;
            }
        }

How do I check if the same user is part of ADgroup2 , ADGroup3,.. etc.

I searched here in the forums and google but couldnt find efficient solution. One way to acheive this is by defining multiple groups and using OR in the if clause check for all the groups..see below

EX:

     GroupPrincipal group1 = GroupPrincipal.FindByIdentity(ctx, "ADGROUP1");
         GroupPrincipal group2 = GroupPrincipal.FindByIdentity(ctx, "ADGROUP2");
 if (user != null)
            {
                if (user.IsMemberOf(group) ||user.IsMemberOf(group1) || user.IsMemberOf(group2) )
                {
                    //Enable certain Form Buttons and objects for IT Users
                    authTbox.Visible = true;
                }
            }

Since I will have to search for 10 such groups I am jus wondering if there is a efficient way to acheive this.

1

There are 1 answers

1
Jirajha On BEST ANSWER

Put your desired groups into an Array, List<T> or other IEnumerable<T> Container and loop over them:

List<GroupPrincipal> groupList = new List<GroupPrincipal>
{
    GroupPrincipal.FindByIdentity(ctx, "ADGROUP1"),
    GroupPrincipal.FindByIdentity(ctx, "ADGROUP1")
    // ...
}
foreach(var group in groupList) 
{
    if(user.IsMemberOf(group)
    {
        // do something
    }
}

It's the most straightforward. This way you could also define each group within a confifg file or in a database and simply get everything you need.

If you need easy mass confirmation, there's the Enumerable.All<TSource> Method:

List<GroupPrincipal> groupList = new List<GroupPrincipal>
{
    GroupPrincipal.FindByIdentity(ctx, "ADGROUP1"),
    GroupPrincipal.FindByIdentity(ctx, "ADGROUP1")
    // ...
}
if(groupList.All(g => user.IsMemberOf(g)) 
{ 
    // do something 
}

As a little sidenote: Depending on your usecase, you might want to set a controlelement to enabled / disabled rather than visibility. This way you only need to maintain one interface layout.