In a web app, we\'re looking to display a list of sam accounts for users that are a member of a certain group. Groups could have 500 or more members in many cases and we need t
Similar to your first option, I created a hashset from the list. The larger the group the longer it takes to verify membership. However it is consistent for successful and unsuccessful membership queries. To iterate through a large group would sometime take 3x longer if the account wasn't a member whereas this method is the same every time.
using(PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
using(GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "groupName"))
{
List members = group.GetMembers(true).Select(g => g.SamAccountName).ToList();
HashSet hashset = new HashSet(members, StringComparer.OrdinalIgnoreCase);
if(hashset.Contains(someUser)
return true;
}
Group membership in Active Directory shouldn't frequently change. For this reason, consider caching group membership to make lookups quicker. Then update the cached group membership every hour or whatever makes the most sense for your environment. This will greatly enhance performance and reduce congestion on the network and domain controllers.
One caveat is if important/restricted information is being protected and there's a need for stronger security controls. Then directly querying Active Directory is the way to go as it ensures you have the most current membership information.