Skip to content

Instantly share code, notes, and snippets.

@MMF
Last active October 4, 2021 18:19
Show Gist options
  • Save MMF/e4fd0f381f7405aa170568fdca04ab5b to your computer and use it in GitHub Desktop.
Save MMF/e4fd0f381f7405aa170568fdca04ab5b to your computer and use it in GitHub Desktop.
Authenticate user with Active Directory
using System;
using System.Configuration;
using System.DirectoryServices;
namespace StrategicPlans.Helpers
{
public class ActiveDirectoryHelper
{
public string ActiveDirectoryServerPath { get; set; }
public ActiveDirectoryHelper()
{
// read active directory path from AppConfig
// example LDAP://serverName
ActiveDirectoryServerPath = ConfigurationManager.AppSettings["ActiveDirectoryPath"];
}
/// <summary>
/// creates new ActiveDirectoryHelper.
/// </summary>
/// <param name="ADPath">active directory server path</param>
public ActiveDirectoryHelper(string ADPath)
{
ActiveDirectoryServerPath = ADPath;
}
/// <summary>
/// authenticates user with active directory
/// </summary>
/// <param name="username">active directory username</param>
/// <param name="password">active directory user's password</param>
/// <returns></returns>
public bool IsAuthenticated(string username, string password)
{
bool isAuthenticated = false;
try
{
DirectoryEntry de = new DirectoryEntry(ActiveDirectoryServerPath, username, password, AuthenticationTypes.Secure);
var x = de.Name;
DirectorySearcher ds = new DirectorySearcher(de);
var sr = ds.FindOne();
isAuthenticated = true;
}
catch (Exception)
{
}
return isAuthenticated;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment