Reputation: 405
I am writing a method to determine if a user exists in an Active Directory Group. I may not know this user's password but I do have another username/password in this Active Directory Group. Is there a more efficient way to do this? Setting the SamAccountName property and the call to userFound.GetGroups() seems to be bottlenecks.
Any suggestions are appreciated.
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ipaddress, remoteDomainAndUserName, password))
{
UserPrincipal qbeUser = new UserPrincipal(pc);
try
{
qbeUser.SamAccountName = lookUpUserName; // don't know password of this user
aDResult = ADResult.Valid; // right now remoteDomainAndUserName/password is valid on the domain, don't know if lookUpUserName is a valid user yet
}
catch (Exception e)
{
return ADResult.InvalidNonLookupID;
}
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
foreach (var found in srch.FindAll())
{
UserPrincipal userFound = found as UserPrincipal;
if (userFound != null)
{
foreach (Principal p in userFound.GetGroups())
{
if (p.SamAccountName.ToLower().Trim() == groupName)
{
bool isEnabled = true;
if (userFound.Enabled.HasValue)
{
isEnabled = userFound.Enabled.Value;
}
if (isEnabled)
return ADResult.ValidInGroup;
else
return ADResult.DisabledInGroup;
}
else
aDResult = ADResult.InvalidInGroup;
}
}
}
}
}
catch (PrincipalServerDownException e)
{
// cannot connect to AD
aDResult = ADResult.Offline;
}
catch (LdapException e)
{
// cannot connect to AD
aDResult = ADResult.Offline;
}
catch (Exception e)
{
// cannot connect to AD
aDResult = ADResult.Offline;
}
Upvotes: 0
Views: 4101
Reputation: 10765
//This is a method I use in a WCF web service I created
//userName is the sAMAccount name of the user
//groupName is the AD group
public bool IsMemberOfGroup(string groupName, string userName)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, userName);
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupName);
if (group == null)
return false;
if (user != null)
return group.Members.Contains(user);
}
catch (System.Exception ex)
{
//Log exception
}
return false;
}
Upvotes: 1