我正在编写一种方法来确定用户是否存在于Active Directory组中。我可能不知道该用户的密码,但我在此Active Directory组中有另一个用户名/密码。有没有更有效的方法来做到这一点?设置SamAccountName属性和调用userFound.GetGroups()似乎是瓶颈。
任何建议都表示赞赏。
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;
}
答案 0 :(得分:0)
//This is a method I use in a WCF web service I created
//userName is the domain 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;
}