在 DirectoryEntry 上使用“组”属性有两个已知问题:
- 它不会显示用户所在的“默认组”(通常是“用户”)
- 它不会显示嵌套组成员身份
因此,如果用户是组 A 的成员,而该组又是组 B 的成员,那么在 Windows 中,这意味着该用户也是组 B 的成员。但是,DirectoryEntry 不会显示该嵌套组会员资格。
这是我所知道的对于直接 Active Directory(没有 Exchange)的两个唯一限制。
获取默认组有点复杂,但我确实有一个代码示例。
private string GetPrimaryGroup(DirectoryEntry aEntry, DirectoryEntry aDomainEntry)
{
int primaryGroupID = (int)aEntry.Properties["primaryGroupID"].Value;
byte[] objectSid = (byte[])aEntry.Properties["objectSid"].Value;
StringBuilder escapedGroupSid = new StringBuilder();
// Copy over everything but the last four bytes(sub-authority)
// Doing so gives us the RID of the domain
for(uint i = 0; i < objectSid.Length - 4; i++)
{
escapedGroupSid.AppendFormat("\\{0:x2}", objectSid[i]);
}
//Add the primaryGroupID to the escape string to build the SID of the primaryGroup
for(uint i = 0; i < 4; i++)
{
escapedGroupSid.AppendFormat("\\{0:x2}", (primaryGroupID & 0xFF));
primaryGroupID >>= 8;
}
//Search the directory for a group with this SID
DirectorySearcher searcher = new DirectorySearcher();
if(aDomainEntry != null)
{
searcher.SearchRoot = aDomainEntry;
}
searcher.Filter = "(&(objectCategory=Group)(objectSID=" + escapedGroupSid.ToString() + "))";
searcher.PropertiesToLoad.Add("distinguishedName");
return searcher.FindOne().Properties["distinguishedName"][0].ToString();
}
获得嵌套组也需要几个步骤,如果这是问题所在,我将不得不寻找解决方案。
马克
PS:作为旁注 - 你到底为什么要打“DirectoryEntry.Invoke(“groups”,null)”电话?为什么不只枚举 DirectoryEntry.Properties["memberOf"] 属性,它是多值的(包含多个值)并且其中包含组的 DN(可分辨名称)?
foreach(string groupDN in myUser.Properties["memberOf"])
{
string groupName = groupDN;
}
或者,如果您使用的是 .NET 3.5,则可以使用 S.DS.AccountManagement 中的新安全主体类。其中之一是“UserPrincipal”,它有一个名为“GetAuthorizationGroups()”的方法,可以为您完成所有这些艰苦的工作——基本上是免费的!
请参阅一篇出色的MSDN 文章,该文章为您描述了这些新的 .NET 3.5 S.DS 功能。