假设正确设置了活动目录,我正试图找到一种方法来确定两个人是否来自同一个位置。我能够绕过它的唯一方法是找到一种方法来确定他们的目录条目是否位于同一个OU中。所以目前,这就是我现在吐痰的原因:
private bool ComparePeople()
{
var user1Guid = "aaa";
var user2Guid = "bbb";
var expr = @"CN=.*?,";
var user1OU = Regex.Replace(GetUserDN(user1Guid), expr, string.Empty);
var user2OU = Regex.Replace(GetUserDN(user2Guid), expr, string.Empty);
return user1OU == user2OU;
}
private string GetUserDN(string userGuid)
{
using(var entry = new DirectoryEntry(string.format("LDAP://<GUID={0}>", userGuid)))
{
using(var search = new DirectorySearcher(entry))
{
search.PropertiesToAdd.Add("distinguishedName");
var result = search.FindOne().GetDirectoryEntry();
if(result != null && result.Properties["distinguishedName"].Count > 0)
{
return result.Properties["distinguishedName"].Value.ToString();
}
else return "";
}
}
}
我还没有测试过这个,但我觉得它会起作用。它基本上找到了用户的专有名称,给他们的Guid。然后它从DN中删除CN,基本上找到该用户的目录条目/ OU的路径。但是,它似乎有点复杂。有没有人有任何意见或建议来简化这个?
答案 0 :(得分:1)
如果我理解正确,您正在尝试找出两个用户帐户是否位于同一个OU(组织单位)内 - 对吗?
我要做的是阅读两个用户帐户的父 - 如果父匹配,那么它们就在同一个OU中。
如果您使用的是.NET 3.5及更高版本,则应查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a two users
UserPrincipal user1 = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, user1Guid);
UserPrincipal user2 = UserPrincipal.FindByIdentity(ctx, IdentityType.Guid, user2Guid);
if(user1 != null && user2 != null)
{
DirectoryEntry dirEntry1 = user1.GetUnderlyingObject() as DirectoryEntry;
DirectoryEntry dirEntry2 = user2.GetUnderlyingObject() as DirectoryEntry;
// if both are OK, get the parents and compare their GUID
if(dirEntry1 != null && dirEntry2 != null)
{
DirectoryEntry parent1 = dirEntry1.Parent;
DirectoryEntry parent2 = dirEntry2.Parent;
bool areInSameOU = (parent1.Guid == parent2.Guid);
}
}
新的S.DS.AM让您可以轻松地与AD中的用户和群组一起玩!