通过LDAP登录时获取用户AD组



我试图在验证用户时获取组列表。仍然得到0个结果。不幸的是,我没有用于测试的环境,所以我无法调试此代码(只能通过记录器(。没有结果,也没有例外。

private LdapResponce IsAuthenticated(string ldap, string usr, string pwd, out List<string> groups)
{
List<string> result = new List<string>();
try
{
using (var searcher = new DirectorySearcher(new DirectoryEntry(ldap, usr, pwd)))
{
searcher.Filter = String.Format("(&(objectCategory=group)(member={0}))", usr);
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("cn");
_loggingService.Info(searcher.FindAll().Count.ToString());// here i'm getting 0
foreach (SearchResult entry in searcher.FindAll())
{
try
{
if (entry.Properties.Contains("cn"))
result.Add(entry.Properties["cn"][0].ToString());
}
catch (NoMatchingPrincipalException pex)
{
continue;
}
catch (Exception pex)
{
continue;
}
}
}
groups = result;
}
catch (DirectoryServicesCOMException cex)
{
groups = new List<string>();
if (cex.ErrorCode == -2147023570) return LdapResponce.WrongPassword;
return LdapResponce.Error;
}
catch (Exception ex)
{
groups = new List<string>();
return LdapResponce.Error;
}
return LdapResponce.Passed;
}

将其添加到程序的顶部使用System.DirectoryServices.AccountManagement;

使用此函数并传递用户名和您要查看的组是否在其中。如果该组嵌套了一个组,它将在嵌套的组中查看用户是否也在该组中。

公共静态布尔值fctADIsInGroup(字符串LSUserName,字符串LSGroupName({布尔LBReturn=false;

// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "Put your domain name here. Right click on My computer and go to properties to see the domain name");
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, LSUserName);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, LSGroupName);
if (user != null)
{
// check if user is member of that group
if (user.IsMemberOf(group))
{
LBReturn = true;
}
else
{
var LSAllMembers = group.GetMembers(true);
foreach(var LSName in LSAllMembers)
{
string LSGPUserName = LSName.SamAccountName.ToUpper();
if (LSGPUserName == PSUserName.ToUpper())
{
LBReturn = true;
}
}
}
}
return LBReturn;
}

最新更新