繁体   English   中英

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

[英]How to determine the type (AD User vs. AD Group) of an account?

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

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

任何意见表示赞赏。 谢谢。

你使用的是什么版本的.NET??

如果您使用的是 .NET 3.5,请参阅这篇出色的MSDN 文章,了解 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();
    }
}

马克

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

考虑使用objectClass代替:

SearchResult sr = ds.FindOne();
bool isUser = sr.Properties["objectClass"]?.Contains("user") == true;
// OR
bool isGroup = sr.Properties["objectClass"]?.Contains("group") == true;
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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM