How do I connect to a locally installed OpenLDAP service?

前端 未结 1 1577
傲寒
傲寒 2021-01-24 12:50

I\'ve been banging my head against the .Net 3.5 PrincipalContext, trying to establish a connection to OpenLDAP that is installed on the same machine as my Visual Studio 2010 IDE

相关标签:
1条回答
  • 2021-01-24 13:41

    Your first problem is using the System.DirectoryServices namespace. The classes in there only work well with Active Directory. I've long ago abandoned it for the System.DirectoryServices.Protocols namespace as well as most other people. Here's some code you can use to get you started in connecting.

    var host = "localhost:389";
    var credential = new NetworkCredential("user", "secret");
    
    using (var con = new LdapConnection(host) { Credential = credential, AuthType = AuthType.Basic, AutoBind = false })
    {
        con.SessionOptions.ProtocolVersion = 3;
        con.SessionOptions.VerifyServerCertificate = new VerifyServerCertificateCallback(VerifyCertDelegate);
        //con.SessionOptions.StartTransportLayerSecurity(new DirectoryControlCollection());
        con.Bind()
        //Do other ldap operations here such as setting the user password
        var pass = "newpass";
        var req = new ModifyRequest
        {
            DistinguishedName = "cn=user,ou=test,dc=example,dc=com"
        };
    
        var dam = new DirectoryAttributeModification
        {
            Name = "userPassword",
            Operation = DirectoryAttributeOperation.Replace
        };
        dam.Add(pass);
        req.Modifications.Add(dam);
    
        con.SendRequest(req);
    }
    

    Notice that in the above TLS is turned off. If you want a secure connection use ssl on port 636. The microsoft ldap libraries have a race condition that will cause your cpu to spike in an infinite loop when two simultaneous ldap calls are made such as in a web server environment.

    0 讨论(0)
提交回复
热议问题