Sometimes, we need to authenticate users using Active Directory. Below provided C# code will help you for the same. You just need to add reference to System.DirectoryServices.dll.
using System.DirectoryServices;
/// <summary>
/// Determines whether the specified domain is authenticated.
/// </summary>
/// <param name=”domain”>The domain.</param>
/// <param name=”username”>The username.</param>
/// <param name=”pwd”>The PWD.</param>
/// <returns><c>true</c> if the specified domain is authenticated; otherwise, <c>false</c>.</returns>
/// <exception cref=”System.Exception”>Error occurred while authenticating user. + ex.Message</exception>
public bool IsAuthenticated(string domain, string username, string pwd)
{
string domainAndUsername = domain + @”\” + username;
DirectoryEntry entry = new DirectoryEntry(this.activeDirectoryPath, domainAndUsername, pwd, AuthenticationTypes.Secure);
try
{
// Bind to the native AdsObject to force authentication.
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = “ (SAMAccountName = ” + username + “)”;
search.PropertiesToLoad.Add(“distinguishedName”);
SearchResult result = search.FindOne();
if (null == result)
{
return false;
}
}
catch (Exception ex)
{
throw new Exception(“Error occurred
while authenticating user.” + ex.Message);
}
}
//You can consume the function as below:
if (true == IsAuthenticated(domainName, userId, txtPassword.Text))
{
// Authenticated…PASSED
}
return true;
} Enjoy Coding!