This tutorial will cover how to login with AD in simple step with C#. As this is common and usual practice for most system, maybe its not helping you much.

First, we need this System.DirectoryServices in our code

using System.DirectoryServices;

 

In submit form code, we send username and password to AD function to retrieve credential

[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 AD service are call here

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.");
	}
}

Happy coding and hoping can give you rough idea how to connect your login form with AD.

C# Login Form with Active Directory AD
Tagged on:

One thought on “C# Login Form with Active Directory AD

Leave a Reply

Your email address will not be published. Required fields are marked *