Check LDAP server connection from C#.NET 4.5.1 without user name and password

1.4k views Asked by At

The task is to create a simple WebAPI application to test the connection to our LDAP server. I am using C# & .NET 4.5.1. The WebAPI application is in our DMZ (not on any domain).

I have created a simple DirectorySearcher lookup that works but requires a username and password.

How would this application check the access to our LDAP server without a username and password?

Here is my latest code. I am attempting to login with an invalid user name and password. If this fails with a "Login Failed" message then I know I have connected with the LDAP server. Seems like a hack though. Would like a better solution.

    public Task<HttpResponseMessage> Ldap()
    {
        const string user = "0000";
        const string pass = "0000";
        const string messageTemplate = "{0} {1} {2} | LDAP: {3}";

        HttpResponseMessage response;
        var userName = String.Format("CN={0},OU=Users,DC=somelocation,DC=Org", user);
        var path = "LDAP://ldap.somelocation.org/" + userName;

        try
        {
            var directorySearcher = new DirectorySearcher
            {
                SearchRoot = new DirectoryEntry(path, userName, pass, AuthenticationTypes.ReadonlyServer),
                SearchScope = SearchScope.Subtree
            };
            directorySearcher.PropertiesToLoad.AddRange(new[]
            {
              "givenName"
            });
            var entry = directorySearcher.FindOne().GetDirectoryEntry();
            if (entry.Properties.Count > 0 && entry.Properties["givenName"].Value != null)
            {
                response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(messageTemplate 
                        .FormatWith(ApiFriendlyName, BuildLabel, BuildNumber,
                            entry.Properties["givenName"].Value))
                };
            }
            else
            {
                response = new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new StringContent(messageTemplate 
                        .FormatWith(ApiFriendlyName, BuildLabel, BuildNumber, "User not found."))
                };
            }
        }
        catch (Exception ex)
        {
            response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(messageTemplate 
                    .FormatWith(ApiFriendlyName, BuildLabel, BuildNumber, 
                        ex.Message.Contains("Logon failure")
                        ? "Connection made"
                        : "Connection failure"))
            };
        }
        return Task.FromResult(response);
    }
0

There are 0 answers