【问题标题】:Get UserPrincipal by employeeID通过employeeID获取UserPrincipal
【发布时间】:2014-05-28 15:49:42
【问题描述】:

我已经实现了 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 的最佳方法是什么?

【问题讨论】:

    标签: c# asp.net-4.0 account-management


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我知道这是一篇旧帖子,但如果它运作良好,我会尝试并标记答案。谢谢!
    【解决方案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 的强类型属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多