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.
Put your desired groups into an
Array
,List<T>
or otherIEnumerable<T>
Container and loop over them: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: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.