2011-11-09 33 views
2

我在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; 
} 

在一个单独的逻辑我试图用一个用户名来检索用户从服务器返回:在运行于C#应用程序我的客户端机器,我可以使用下面的函数进行身份验证对Active Directory服务器用户。我使用了以下功能:

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 

任何帮助将不胜感激,我已经花了我的大部分一天的故障排除和研究这个小小的bug子手,我认为它可能是我忽略的一些小东西。

回答

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中的用户和群组一起玩:

+0

谢谢你们两位,我会尝试一下你的建议。我的返回null是我从调试中遗留下来的一个错误,因为我之前有一个if else子句,就像你向我展示的那样。我使用UserPrincipal和DirectoryEntry的原因是要习惯LDAP的API并学习它们。我会采纳你们两个的建议并进行测试。我稍后会更新我的结果。 – Fylix

0

我觉得你的代码有几个问题:

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

希望,这有助于。

+0

谢谢,我认为我错误地删除了一行,我曾经在那里有一个if else条件。返回null只是我做的一个测试。 – Fylix

相关问题