如何使用c#使用其凭据连接到LDAPserver

时间:2011-12-21 07:22:29

标签: vb.net asp.net-membership

我正在尝试使用以下代码连接到ldap服务器。

        Dim xd As New XmlDocument()
        Dim domainAndUsername As String = String.Empty
        Dim userName As String = String.Empty
        Dim passWord As String = String.Empty
        Dim at As AuthenticationTypes = AuthenticationTypes.Anonymous
        Dim sb As New StringBuilder()



        domainAndUsername = "LDAP://MARS-AD\kumaravi:J647d197@ISXDC101.DC.MARS:389/OU=EXD,OU=People,OU=EMEAI,OU=Mars,OU=IT-Services,DC=Mars-AD,DC=Net"
        userName = "username"
        passWord = "password"

        at = AuthenticationTypes.Secure

        'Create the object necessary to read the info from the LDAP directory
        Dim entry As New DirectoryEntry(domainAndUsername, userName, passWord, at)



        Dim mySearcher As New DirectorySearcher(entry)
        Dim results As SearchResultCollection
        mySearcher.Filter = filter

它给出以下错误消息。 “服务器无法运行”。

1 个答案:

答案 0 :(得分:0)

如果您使用的是.NET 3.5或更高版本,则可以使用PrincipalSearcher和“按示例查询”主体进行搜索:

// create your domain context - this will automatically connect to the 
// current domain of your machine
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a UserPrincipal 
UserPrincipal qbeUser = new UserPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

// find all matches
foreach(var found in srch.FindAll())
{
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....          
}

您可以在UserPrincipal上指定任何属性,并将其用作PrincipalSearcher的“按示例查询”。

如果您还没有 - 绝对阅读MSDN文章Managing Directory Security Principals in the .NET Framework 3.5,该文章很好地展示了如何充分利用System.DirectoryServices.AccountManagement

中的新功能