C# Login Form with Active Directory AD
This tutorial will cover how to make login form with Microsoft Active Directory (AD) in simple step with CSharp (C#). As this is common and usual practice for most system nowadays, maybe its will helping you a bit. Its very simple and straight forward to use Active Directory with login form with .net C#
First, we need this System.DirectoryServices in our code. This is compulsory to make us connect with AD. Call the library System.DirectoryServices
using System.DirectoryServices;
In submit form code, we send username and password to Active Directory AD function to retrieve and pair user credential either valid or not
[HttpPost]
public ActionResult Login(LoginModel login, string returnUrl)
{
string uname = HttpUtility.HtmlEncode( login.UserName);
login.Password = HttpUtility.HtmlEncode(login.Password);
try
{
string flag = GetActiveDirectoryData(uname, login.Password);
if (flag != null)
{
//code
}else{
//code
}
}
catch (Exception ex)
{
ViewBag.errorMsg = ex.Message;
return View();
}
}
}
This are important part, our Active Directory (AD) service are call from here. Make sure path to LDAP are correct or forever non working. If not sure can contact your sysadmin or awesome server guy for correct path
private static string GetActiveDirectoryData(string UserID, string Password)
{
try
{
DirectoryEntry DEntry = new DirectoryEntry("LDAP://path.com", UserID.Trim(), Password);
DirectorySearcher DSearch = new DirectorySearcher(DEntry);
DSearch.Filter = string.Format("(sAMAccountName={0})", UserID.Trim());
SearchResult SResult = DSearch.FindOne();
DirectoryEntry _DEntry = new DirectoryEntry();
try
{
_DEntry.Path = SResult.Path;
}
catch (Exception ex)
{
_DEntry.Close();
_DEntry.Dispose();
throw new Exception(ex);
}
_DEntry.AuthenticationType = AuthenticationTypes.Secure;
_DEntry.Username = string.Format("Domain\\{0}", UserID.Trim());
_DEntry.Password = Password;
string ErrorMsg = "";
string Result = "";
try
{
Result = _DEntry.Username.Replace("Domain\\", "");
}
catch (Exception ex)
{
ErrorMsg = ex.Message;
}
_DEntry.Close();
_DEntry.Dispose();
DEntry.Close();
if (!string.IsNullOrEmpty(ErrorMsg))
{
throw new Exception(ErrorMsg);
}
else
{
return Result;
}
}
catch (Exception ex)
{
throw new Exception(“Username/Password entered is incorrect.”);
}
}
Thats it. Thats All. Happy coding and i hope this snippet can give you rough idea how to connect your login form with Active Directory (AD) with login form or whatever you want to integrate.
Here also few related post that you maybe want to check
easy to hadam. TQ