如何确定帐户的类型(AD用户 vs. AD组)?

3

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

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

任何意见都将不胜感激。 谢谢。

3个回答

9
你使用的是哪个版本的.NET?
如果你使用的是.NET 3.5,可以查看这篇微软官方网站文章,了解Active Directory接口发生的重大变化。
如果你使用的是.NET 3.5,你可以这样编写代码:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "YOURDOMAIN");
Principal myObject = Principal.FindByIdentity(ctx, "your name value");

通常,您只需要传递用户名-反斜杠后面的部分-而不是整个DOMAIN\USERNAME字符串。
此“Principal”现在可以是UserPrincipal或GroupPrincipal(或者可能是其他类型的principal,例如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。尽管需要更多的代码来完成这个任务,但它确实有效。 - ddou
第二种解决方案对我来说不起作用。奇怪的是,我得到的是入口路径而不是Person/Group。 - Just Shadow

1

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

考虑改用objectClass

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

0
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接