e-Zest members share technology ideas to foster digital transformation.

How to Retrieve Active Directory Information for Authentication in ASP.NET

Written by Swapna Patne | Jan 14, 2013 10:48:02 AM

Introduction

Hello Friends, I would like to share some of my interesting findings for retrieving the Active Directory information for authentication in web application using C#.NET.

So let’s move on to the implementation details.

Life has been made easy with the introduction of the System.DirectoryServices.dll library in .Net Framework. There's a simple function which I have written that does the Forms/Window authentication to permit users to authenticate against Active Directory using the Lightweight Directory Access Protocol (LDAP).

This custom function basically takes a username, and tries to authenticate it on the given LDAP (Active Directory).

The code below demonstrates the same.

Add the reference to the System.DirectoryServices.dll. Then, include the library in your page:

using System.DirectoryServices;

I have created a custom static class for accessing all Active Directory properties

public static class ADProperties
{
	public const string ACCOUNTEXPIRES = "accountExpires";
	public const string ADMINCOUNT = "adminCount";
	public const string BADPASSWORDTIME = "badPasswordTime";
	public const string BADPWDCOUNT = "badPwdCount";
	public const string CITY = "l";
	public const string CODEPAGE = "codePage";
	public const string COMPANY = "company";
	public const string CONTAINERNAME = "cn";
	public const string COUNTRY = "co";
	public const string COUNTRYCODE = "countryCode";
	public const string COUNTRYNOTATION = "c";
	public const string DEPARTMENT = "department";
	public const string DIRECTREPORTS = "directReports";
	public const string DISPLAYNAME = "displayName";
	public const string DISTINGUISHEDNAME = "distinguishedName";
	public const string DSCOREPROPAGATIONDATA = "dSCorePropagationData";
	public const string EMAILADDRESS = "mail";
	public const string EXTENSION = "ipPhone";
	public const string FAX = "facsimileTelephoneNumber";
	public const string FIRSTNAME = "givenName";
	public const string HOMEMDB = "homeMDB";
	public const string HOMEMTA = "homeMTA";
	public const string HOMEPHONE = "homePhone";
	public const string INSTANCETYPE = "instanceType";
	public const string LASTLOGOFF = "lastLogoff";
	public const string LASTLOGON = "lastLogon";
	public const string LASTLOGONTIMESTAMP = "lastLogonTimestamp";
	public const string LASTNAME = "sn";
	public const string LEGACYEXCHANGEDN = "legacyExchangeDN";
	public const string LOGINNAME = "sAMAccountName";
	public const string LOGONCOUNT = "logonCount";
	public const string MAILNICKNAME = "mailNickname";
	public const string MANAGER = "manager";
	public const string MDBUSEDEFAULTS = "mDBUseDefaults";
	public const string MEMBEROF = "memberOf";
	public const string MIDDLENAME = "initials";
	public const string MOBILE = "mobile";
	public const string MSEXCHHOMESERVERNAME = "msExchHomeServerName";
	public const string MSEXCHMAILBOXGUID = "msExchMailboxGuid";
	public const string MSEXCHMAILBOXSECURITYDESCRIPTOR = "msExchMailboxSecurityDescriptor";
	public const string MSEXCHPOLICIESINCLUDED = "msExchPoliciesIncluded";
	public const string MSEXCHRECIPIENTDISPLAYTYPE = "msExchRecipientDisplayType";
	public const string MSEXCHRECIPIENTTYPEDETAILS = "msExchRecipientTypeDetails";
	public const string MSEXCHUSERACCOUNTCONTROL = "msExchUserAccountControl";
	public const string MSEXCHVERSION = "msExchVersion";
	public const string NAME = "name";
	public const string NTSECURITYDESCRIPTOR = "nTSecurityDescriptor";
	public const string OBJECTCATEGORY = "objectCategory";
	public const string OBJECTCLASS = "objectClass";
	public const string OBJECTGUID = "objectGUID";
	public const string OBJECTSID = "objectSid";
	public const string PAGER = "pager";
	public const string PHYSICALDELIVERYOFFICENAME = "physicalDeliveryOfficeName";
	public const string POSTALCODE = "postalCode";
	public const string PRIMARYGROUPID = "primaryGroupID";
	public const string PROXYADDRESSES = "proxyAddresses";
	public const string PWDLASTSET = "pwdLastSet";
	public const string SAMACCOUNTTYPE = "sAMAccountType";
	public const string SERVICEPRINCIPALNAME = "servicePrincipalName";
	public const string SHOWINADDRESSBOOK = "showInAddressBook";
	public const string STATE = "st";
	public const string STREETADDRESS = "streetAddress";
	public const string TITLE = "title";
	public const string USERACCOUNTCONTROL = "userAccountControl";
	public const string USERPRINCIPALNAME = "userPrincipalName";
	public const string USNCHANGED = "uSNChanged";
	public const string USNCREATED = "uSNCreated";
	public const string WHENCHANGED = "whenChanged";
	public const string WHENCREATED = "whenCreated";
}

You can use the following function along with forms based authentication or it can used just to check a user's credentials. It takes the following input variables:

username: The user's account name. It can be prefixed by the domain;

e.g., mydomaintom or just username ex: tom..

public void GetActiveDirectoryDetails(string username)
    {
DirectorySearcherdirectorysearcher = new DirectorySearcher();
        var path = directorysearcher.SearchRoot.Path;
        DirectoryEntry dirEntry = new DirectoryEntry(path);
        DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry) { Filter = "(" + ADProperties.LOGINNAME + "=" + username+ ")" };

        SearchResult result = dirSearcher.FindOne();

        if (result != null)
        {
            if (result.Properties.Contains(ADProperties.FIRSTNAME))
            {
                firstName = Convert.ToString(result.Properties[ADProperties.FIRSTNAME][0]);
            }
            if (result.Properties.Contains(ADProperties.LASTNAME))
            {
                lastName = Convert.ToString(result.Properties[ADProperties.LASTNAME][0]);
            }
            if (result.Properties.Contains(ADProperties.EMAILADDRESS))
            {
                emailId = Convert.ToString(result.Properties[ADProperties.EMAILADDRESS][0]);
            }
            if (result.Properties.Contains(ADProperties.DEPARTMENT))
            {
                department = Convert.ToString(result.Properties[ADProperties.DEPARTMENT][0]);
            }

        }
    }

The below code will help you to fetch the Groups from the Active Directory

public string GetGroups(string param)
{
    DirectorySearcher directorysearcher = new DirectorySearcher();
    var path = directorysearcher.SearchRoot.Path;

    DirectoryEntry dirEntry = newDirectoryEntry(path);
    DirectorySearcher dirSearcher = new DirectorySearcher(dirEntry) { Filter = "(" + ADProperties.LOGINNAME + "=" + param + ")" };

    SearchResult result = dirSearcher.FindOne();
    StringBuildergroupNames = new StringBuilder();

    try
    {

        int propertyCount = result.Properties["memberOf"].Count;
        string dn;
        int equalsIndex, commaIndex;

        for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
        {
            dn = (string)result.Properties["memberOf"][propertyCounter];
            equalsIndex = dn.IndexOf("=", 1);
            commaIndex = dn.IndexOf(",", 1);
            if (-1 == equalsIndex)
            {
                return null;
            }
            groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
            groupNames.Append("|");
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Error obtaining group names. " + ex.Message);
    }

	return groupNames.ToString();
}

So friends, I hope this will help you to get all Active Directories in a single custom file.