正在检索用户的自定义Active Directory属性
本文关键字:Active Directory 属性 自定义 检索 用户 | 更新日期: 2023-09-27 18:20:59
我一直在尝试检索在Active Directory用户上设置的两个自定义属性,但似乎我一直在获取属性的恒定列表(在2个不同的AD服务器上测试)
假设我试图获取的属性是prop1
和prop2
,那么我在以下代码中做错了什么:
List<String> nProps = new List<string>();
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");
foreach (DirectoryEntry child in directoryEntry.Children)
{
// No filtering; ignore schemes that are not User schemes
if (child.SchemaClassName == "User")
{
foreach (var sVar in child.Properties.PropertyNames)
nProps.Add(sVar.ToString());
break;
}
}
nProps
不包含我的任何自定义属性(不是prop1
也不是prop2
)
(它确实包含其他属性,如BadPasswordAttempts、Username等)
有什么想法吗?
您确定已设置属性吗?如果没有设置,它们就不会被列为属性
如果您正在查找特定的属性,我建议您使用DirectorySearcher
以下示例是获取给定用户的公司属性。请注意,您首先验证属性是否存在,然后提取它。
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://DOM");
//Create a searcher on your DirectoryEntry
DirectorySearcher adSearch= new DirectorySearcher(directoryEntry);
adSearch.SearchScope = SearchScope.Subtree; //Look into all subtree during the search
adSearch.Filter = "(&(ObjectClass=user)(sAMAccountName="+ username +"))"; //Filter information, here i'm looking at a user with given username
SearchResult sResul = adSearch.FindOne(); //username is unique, so I want to find only one
if (sResult.Properties.Contains("company")) //Let's say I want the company name (any property here)
{
string companyName = sResult.Properties["company"][0].ToString(); //Get the property info
}
虽然不能直接回答您的问题,但我们使用以下内容:
public static string GetProperty(string adUserId, string domain, string lDAPLoginId, string lDAPPassword, string propertyName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, lDAPLoginId, lDAPPassword);
UserPrincipal up = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, adUserId);
string result = "";
if (up != null)
{
result = PrincipalGetProperty(up, propertyName);
}
return result;
}