Active Directory Authentication
Introduction
Authenticate users accessing application by using Microsoft Active Directory using Microsoft DirectoryServices.
Background
Security is one of the most important thing while developing an application for an Enterprise. Active Directory is a directory service used to store information about the network resources across a domain and also centralize the network. Using Active directory authentication you can allow users under a domain to access application along with the roles as built in active directory.
Using the code
To use Active Directory authentication DirectoryEntry and DirectorySearcher classes will be used, these classes are part of Microsoft DirectoryServices.
First Add reference to .Net Interop System.DirectoryServices then create instance of DirectoryEntry and DirectorySearcher Class.
private DirectoryEntry entry;
entry = new DirectoryEntry("LDAP://" + oDomainName + "", oUserName,
oPassword, System.DirectoryServices.AuthenticationTypes.Secure);
private DirectorySearcher ds;
entry = new DirectoryEntry("LDAP://" + oDomainName + "", oUserName,
oPassword, System.DirectoryServices.AuthenticationTypes.Secure);
Then made a search in active directory against your login credentials, if searchresult returns object of the user it means that user exist in the Active Directory with the submitted credentials.
The source code also contains a method "GetDomains" which returns an ArrayList having all the domains that are present in the network.
public ArrayList GetDomains()
{
ArrayList arrDomains = new ArrayList();
DirectoryEntry ParentEntry = new DirectoryEntry();
try
{
ParentEntry.Path = "WinNT:";
foreach (DirectoryEntry childEntry in ParentEntry.Children)
{
switch (childEntry.SchemaClassName)
{
case "Domain":
{
arrDomains.Add(childEntry.Name);
break;
}
default:
{
break;
}
}} }
catch (Exception e)
{
}
finally
{
ParentEntry = null;
}
return arrDomains;
}