LDAP SSL check authentication C#

To connect to LDAP I found many developer that use DirectoryEntry and I think this is the most popular solution.
This solution works good if the LDAP is not on SSL or if the certificate is signed by a certification authority NOT self certificate.

public bool SignInLDAP1(string user, string psw, string ldapPath, string domain = null, bool useSSL = false)
{
    try
    {
        var fullUser = user;

        if (!String.IsNullOrEmpty(domain))
            fullUser = domain + "\\" + user;

        var entry = new DirectoryEntry(ldapPath, fullUser, psw);

        if (useSSL)
            entry.AuthenticationType = AuthenticationTypes.SecureSocketsLayer;

        object nativeObject = entry.NativeObject;

        return true;
    }
    catch (Exception ex)
    {
        return false;
    }
}

// sample of usage
var isLogged = SignInLDAP1("user", "psw", "LDAP://myserverName.com/DC=myserver,DC=com", "myserver", false)

As I have said before, this doesn’t work with SLL and self certificated so I change the code.
The fallowing code will work correctly with SSL and without SSL, so if you need only to validate a user account I suggest to use this code instead of the previous

public bool SignInLDAP2(string user, string psw, string ldapPath, string domain = null, bool useSSL = false)
{
    LdapConnection ldapConnection = new LdapConnection(ldapPath);

    if (useSSL)
    {
        ldapConnection.SessionOptions.SecureSocketLayer = true;
        ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
        ldapConnection.AuthType = AuthType.Negotiate;
    }

    //var networkCredential = new NetworkCredential("Hey", "There", "Guy");
    var networkCredential = new NetworkCredential(user, psw, domain);
    try
    {
        ldapConnection.Bind(networkCredential);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

// sample of usage
var isLogged2 = SignInLDAP2("user", "psw", "myserverName.com:636", "myserver", true)
Annunci

Informazioni su Andrea Regoli

Project Manager .Net Developer WPF WP7 Asp.Net c# javascript ajax SQL sharepoint
Questa voce è stata pubblicata in Active Directory, c# e contrassegnata con , , , . Contrassegna il permalink.

Rispondi

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...