I have tried various ways to get the groups associated to an user of the Active Directory, but every method is quite slow.
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain.Text, username.Text, password.Text))
{
UserPrincipal user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, username.Text);
if (user != null)
{
int userGroupTmp = 0;
var group1Principal = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, group1.Text);
var group2Principal = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, group2.Text);
var group3Principal = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, group3.Text);
var group4Principal = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, group4.Text);
if (group1Principal != null && user.IsMemberOf(group1Principal))
{
userGroupTmp = 1;
}
else if (group2Principal != null && user.IsMemberOf(group2Principal))
{
userGroupTmp = 2;
}
else if (group3Principal != null && user.IsMemberOf(group3Principal))
{
userGroupTmp = 3;
}
else if (group4Principal != null && user.IsMemberOf(group4Principal))
{
userGroupTmp = 4;
}
// ...
}
}
It seems that in any case it is slow. I've tried also with user.GetAuthorizationGroups() but I get the same results.
Any suggestion or different method to get the groups?
I've tried different methods and the expectation is a better performance in terms of timing.
I've solved it using another method found at this link: How to get the groups of a user in Active Directory? (c#, asp.net) The method working is the custom GetAdGroupsForUser2: