【问题标题】:How to determine the type (AD User vs. AD Group) of an account?如何确定帐户的类型(AD 用户与 AD 组)?
【发布时间】:2009-12-04 06:09:08
【问题描述】:

我有一个关于确定帐户名称类型(用户或组)的问题。
例如,我有两个字符串,说“Adventure-works\david”和“Adventure-works\admins”, 第一个代表一个名为 david 的用户,第二个代表一个 AD 组。

我的问题是如何确定这些帐户的类型(用户或 AD 组)?有没有方便的方法可以使用?

感谢任何 cmets。 谢谢。

【问题讨论】:

  • 感谢您的回答和提醒。

标签: c# windows active-directory


【解决方案1】:

您使用的是哪个版本的 .NET??

如果您使用的是 .NET 3.5,请参阅这篇出色的 MSDN article,了解 Active Directory 界面如何发生了很大变化。

如果您使用的是 .NET 3.5,您可以编写:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");

通常,您只需要传入用户名 - 反斜杠后的部分 - 而不是整个 DOMAIN\USERNAME 字符串。

这个“主体”现在要么是 UserPrincipal 要么是 GroupPrincipal(或者它可以是其他类型的主体,例如 ComputerPrincipal):

if(myObject is UserPrincipal)
{
    // you have a user
}
else if(myObject is GroupPrincipal)
{
    // you have a group
}

你可以从那里继续。


如果您使用的是 .NET 1.x/2.0/3.0,则必须使用稍微复杂一些的过程来创建 DirectorySearcher 并搜索您的对象:

// create root DirectoryEntry for your search
DirectoryEntry deRoot = new DirectoryEntry("LDAP://dc=YourCompany,dc=com");

// create searcher            
DirectorySearcher ds = new DirectorySearcher(deRoot);

ds.SearchScope = SearchScope.Subtree;

// define LDAP filter - all you can specify is the "anr" (ambiguous name
// resolution) attribute of the object you're looking for
ds.Filter = string.Format("(anr={0})", "YourNameValue");

// define properties you want in search result(s)
ds.PropertiesToLoad.Add("objectCategory");
ds.PropertiesToLoad.Add("displayName");

// search
SearchResult sr = ds.FindOne();

// check if we get anything back, and if we can check the "objectCategory" 
// property in the search result
if (sr != null)
{
    if(sr.Properties["objectCategory"] != null)
    {
       // objectType will be "Person" or "Group" (or something else entirely)
       string objectType = sr.Properties["objectCategory"][0].ToString();
    }
}

马克

【讨论】:

  • 感谢您的帖子,对您有很大帮助。我正在使用.NET 2.0。尽管完成此任务需要更多代码,但它确实有效。
  • 第二种解决方案对我不起作用。奇怪的是,我得到的是入口路径而不是个人/组。
【解决方案2】:

警告:如果使用DirectorySearcher,接受的答案可能失败,因为objectCategory 它不会返回一致的结果。

考虑改用objectClass

SearchResult sr = ds.FindOne();
bool isUser = sr.Properties["objectClass"]?.Contains("user") == true;
// OR
bool isGroup = sr.Properties["objectClass"]?.Contains("group") == true;

【讨论】:

    【解决方案3】:
    using System.DirectoryServices.AccountManagement;
    ...
    ..
    Principal myPrincipal = Principal.FindByIdentity(ctx, "your name value");
    if (myPrincipal.GetType() == typeof(GroupPrincipal)) {
        GroupPrincipal myGroup = (GroupPrincipal)myPrincipal;
    } else {
        UserPrincipal myUser = (UserPrincipal)myPrincipal;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-20
      • 2018-01-12
      • 2014-09-22
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多