无法在C#中检索Active Directory用户

时间:2011-11-09 21:22:20

标签: c# active-directory ldap

我在Window 2008中构建了一个测试Active Directory服务器,我也在其上运行DNS服务器。在运行C#应用程序的客户端计算机上,我可以使用以下函数针对Active Directory服务器对用户进行身份验证:

public static UserPrincipal GetUserPrincipal(string usrName,string pswd,string domainName)
{
   UserPrincipal usr;
   PrincipalContext ad;

   // Enter Active Directory settings
   ad = new PrincipalContext(ContextType.Domain, domainName,usrName,pswd);

   //search user
   usr = new UserPrincipal(ad);
   usr.SamAccountName = usrName;

   PrincipalSearcher search = new PrincipalSearcher(usr);
   usr = (UserPrincipal)search.FindOne();
   search.Dispose();
   return usr;
}

在一个单独的逻辑中,我尝试使用用户名从服务器检索用户。我使用了以下功能:

public static DirectoryEntry CreateDirectoryEntry()
{
   // create AD connection
   DirectoryEntry de = new DirectoryEntry("LDAP://CN=Users,DC=rootforest,DC=com","LDAP","password");
   de.AuthenticationType = AuthenticationTypes.Secure;
   return de;
}

public static ResultPropertyCollection GetUserProperty(string domainName, string usrName)
{
    DirectoryEntry de = CreateDirectoryEntry();
    DirectorySearcher deSearch = new DirectorySearcher();
    deSearch.SearchRoot = de;
    deSearch.Filter = "(SamAccountName=" + usrName + ")";
    SearchResult results = deSearch.FindOne();

    return null;
}

但是,我根本没有从LDAP服务器回复,甚至没有例外。我错过了LDAP服务器上的某些设置,你们中的任何人都能看到我的代码中的缺陷(请不要介意硬代码值,我正在测试这段代码)。

作为我的故障排除的一部分,我确认我可以从客户端计算机ping到rootforest.com。我确认用户的属性samaccountname“LDAP”存在。我的路径似乎是正确的,因为当我进入LDAP服务器并输入:

dsquery user -name LDAP*      

我得到了以下内容:

CN=LDAP L. LDAP,CN=Users,DC=rootforest,DC=com

任何帮助都会非常感激,我花了大部分时间来排除故障并研究这个小虫子,我认为这可能是我忽略的小事。

2 个答案:

答案 0 :(得分:2)

我不明白为什么你在第一个例子中使用了新的PrincipalContext / UserPrincipal内容,但又回到了第二个例子中难以使用的DirectoryEntry内容....没有真的有道理......还有:你的第二个函数GetUserProperty似乎返回null 总是 - 错字或不错?

由于您已经在使用System.DirectoryServices.AccountManagement(S.DS.AM)命名空间,所以也可以将它用于第二项任务!在这里阅读所有相关内容:

基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:

public static ????? GetUserProperty(string domainName, string usrName)
{
   // set up domain context
   PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

   // find a user
   UserPrincipal user = UserPrincipal.FindByIdentity(ctx, usrName);

   if(user != null)
   {
      // return what you need to return from your user principal here
   }
   else
   {
       return null;
   }
}

新的S.DS.AM使得在AD中使用用户和群组变得非常容易:

答案 1 :(得分:0)

我认为您的代码存在一些问题:

  1. 为什么要在null函数中返回GetUserProperty()?您应该返回results
  2. 您在搜索过滤器中使用的属性拼写错误。请改用sSAMAccountName。此外,您的查询扩展为仅搜索用户帐户。以下是一个示例:(&(objectCategory=person)(objectClass=user)(sAMAccountName=usrName))
  3. 您还可以使用UserPrincipal类在Active Directory中搜索身份。 UserPrincipal类提供了一个名为FindByIdentity()的静态方法来搜索用户身份。
  4. 希望,这有帮助。