通过employeeID获取UserPrincipal

本文关键字:UserPrincipal 获取 employeeID 通过 | 更新日期: 2023-09-27 18:05:48

我已经实现了System.DirectoryServices.AccountManagement的身份验证到我的webapps找到用户(UserPrincipal)的身份给定的用户名。但是,在一些情况下,我只需要给定employeeID来获取AD帐户。在AccountManagement中给定employeeID,是否有一种好方法可以获得UserPrincipal(甚至只是sAMAccountName) ?

我目前有这个工作通过用户名抓取用户:

PrincipalContext adAuth = new PrincipalContext(ContextType.Domain, Environment.UserDomainName);
//get user
UserPrincipal usr = UserPrincipal.FindByIdentity(adAuth, username);

我一直在寻找,似乎找不到答案来确认这是否可以或不可以做。如果我不能用AccountManagement做到这一点,那么获得给定employeeID的sAMAccountName的最佳方法是什么?

通过employeeID获取UserPrincipal

您不需要进入System.DirectoryServices.AccountManagement命名空间之外。

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

在本例中,如果没有找到用户,则user对象将为空。如果你想找到一个userprincipal对象的集合,你可以在PrincipalSearcher (ps)对象上使用FindAll方法。

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

所以,我找到了使用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属性。