How to login to Active Directory?

.net-4.0, active-directory, authorization, c#, windows-server

Solution

There you go. This method validates `username/password` against Active Directory, and has been a part of my toolbox of functions for quite some time.

//NOTE: This can be made static with no modifications
public bool ActiveDirectoryAuthenticate(string username, string password)
{
    bool result = false;
    using (DirectoryEntry _entry = new DirectoryEntry())
    {
        _entry.Username = username;
        _entry.Password = password;
        DirectorySearcher _searcher = new DirectorySearcher(_entry);
        _searcher.Filter = "(objectclass=user)";
        try
        {
            SearchResult _sr = _searcher.FindOne();
            string _name = _sr.Properties["displayname"][0].ToString();
            result = true;
        }
        catch
        { /* Error handling omitted to keep code short: remember to handle exceptions !*/ }
    }

    return result; //true = user authenticated!
}

The software executing this must be run on a computer inside the domain, obviously (or you would have no Active Directory to authenticate your credentials against).

Problem

I have a username and password for active directory and I want login to active directory using C#. How I can do this in Windows Forms?

Original source

Related problems