6

我已经实现了 System.DirectoryServices.AccountManagement 以通过给定用户名的身份在我的 webapps 中查找用户 (UserPrincipal) 进行身份验证。但是,我有几种情况需要只给定一个employeeID 来获取AD 帐户。有没有一种好方法可以在 AccountManagement 中获得一个给定员工 ID 的 UserPrincipal(甚至只是 sAMAccountName)?

我目前正在通过用户名来获取用户:

PrincipalContext adAuth = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);

//get user
UserPrincipal usr = UserPrincipal.FindByIdentity(adAuth, username);

我一直在寻找,似乎无法找到答案来确认这是否可以完成。如果我不能用 AccountManagement 做到这一点,那么在给定员工 ID 的情况下获取 sAMAccountName 的最佳方法是什么?

4

2 回答 2

12

您不需要离开 System.DirectoryServices.AccountManagement 命名空间。

UserPrincipal searchTemplate = new UserPrincipal(adAuth);
searchTemplate.EmployeeID = "employeeID";
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);

UserPrincipal user = (UserPrincipal)ps.FindOne();

在此示例中,如果未找到用户,则用户对象将为空。如果要查找 UserPrincipal 对象的集合,可以对 PrincipalSearcher (ps) 对象使用 FindAll 方法。

另请注意,FindOne 方法返回一个 Principal 对象,但我们知道它实际上是一个 UserPrincipal 并且应该这样处理(转换),因为 UserPrincipal 是搜索过滤器的一部分。

于 2015-12-18T00:33:22.717 回答
2

所以,我找到了一种使用 System.DirectoryServices 的方法,如下所示,但它似乎相当冗长:

string username = "";

DirectoryEntry entry = new DirectoryEntry(_path);

//search for a DirectoryEntry based on employeeID
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(employeeID=" + empID + ")";

//username
search.PropertiesToLoad.Add("sAMAccountName");

SearchResult result = search.FindOne();

//get sAMAccountName property
username = result.Properties["sAMAccountName"][0].ToString();

当然,我可以将它用于其他属性,但我真的很喜欢 AccountManagement 的强类型属性。

于 2014-05-28T17:44:27.287 回答