LDAP server could not be contacted when connecting using C#

Viewed 2433

I have written the below code to connect to LDAP server and validate the user credentials.

    public static string AuthFunction_One(string identity, string password, string containerString, string adServerName, bool useLDAPS, IdentityType identityType)
    {

        string failedString = "FAILED";
        string successString = "SUCCESS";
        string returnValue = failedString;
        try
        {
            PrincipalContext ctx = null;

            ctx = new PrincipalContext(ContextType.Domain, "ldap://localhost:10389/dc=example,dc=com", "uid=rish,dc=example,dc=com");

            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(ctx, identityType, identity);
            PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
            if (ctx.ValidateCredentials(identity, password))
            {
                return successString;
            }
            else
            {
                return failedString;
            }
        }
        catch (Exception ex)
        { 
            NLogHelper.GetInstance().Log("ADUtilityClass", "AuthFunction_One", NLog.LogLevel.Debug, "Error in function. Ex: " + ex.ToString());
            return failedString;
        }
    }

This is throwing the below exception.

Exception: Exception thrown: 
'System.DirectoryServices.AccountManagement.PrincipalServerDownException' in System.DirectoryServices.AccountManagement.dll ("The server could not be contacted.")

Below is the LDAP server I am running. enter image description here

When I try to connect through LDAP explorer, it does connect.Below are the configurations I used there.

userdn -> uid=rish,dc=example,dc=com
basedn -> dc=example,dc=com
password -> secret
servername -> localhost
port -> 10389
version -> 3

What am I doing wrong in my C# code? any help would be much appreciated.

0 Answers
Related