Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Bind asynchronously with LdapConnection

While asynchronously requesting the execution of LDAP operations via BeginSendRequest and EndSendRequest is pretty straightforward, I was not able to identify how the binding-process can be done asynchronously.

Is there a possibility to bind asynchronously with the LdapConnection of SDS.P

like image 934
HCL Avatar asked Nov 19 '22 09:11

HCL


1 Answers

Was looking to do async LDAP operations and found this unanswered question. Ended up figuring it out myself:

Assuming that you also want to send/receive a LDAP request asynchronously after Binding (not sure why else you would want to Bind), you can use the AutoBind property on LdapConnection and specify credentials up front in the constructor to achieve an "Asynchronous Bind", by using BeginSendRequest()/EndSendRequest() and letting it handle the Bind internally, in an asynchronous manner.

using System.DirectoryServices.Protocols;
using System.Net;
using System.Threading.Tasks;

// ...

using (var connection = 
    new LdapConnection(
        new LdapDirectoryIdentifier("fqdn.example.com", true, false),
        new NetworkCredential("someuser", "somepassword"),
        AuthType.Basic))
{
    // The Answer...
    connection.AutoBind = true;

    var searchResult = await Task.Factory.FromAsync(
            connection.BeginSendRequest, 
            connection.EndSendRequest,
            new SearchRequest(
                "DC=example,DC=com",
                "(objectClass=user)",
                SearchScope.Subtree,
                "distinguishedname"), 
            PartialResultProcessing.NoPartialResultSupport, 
            null);

    // Profit
}

For brevity, I put the older Asynchronous Programming Model methods (APM) on LdapConnection into the handy wrapper method provided for Task-based Asynchronous Pattern (TAP) so that it may be simply await'ed as expected in modern .Net projects. See: https://learn.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/interop-with-other-asynchronous-patterns-and-types

Doesn't really answer the question precisely, but does show that you don't really have to Bind explicitly yourself and maybe that's why MS didn't bother adding a BeginBind() etc. Hope this helps the next weary programmer wrestling with LDAP interop who comes across it.

like image 74
Bryan W Avatar answered Jan 31 '23 07:01

Bryan W