1

假设活动目录设置正确,我试图找到一种方法来确定两个人是否来自同一位置。我能够解决这个问题的唯一方法是找到一种方法来确定他们的目录条目是否位于同一个 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 的路径。不过,好像有点绕。有没有人有任何意见或建议来简化这一点?

4

1 回答 1

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 中与用户和组一起玩变得非常容易!

于 2012-05-06T07:31:56.750 回答