Thursday, August 15, 2013

Active Directory Services Step by Step


Implementing Active Directory Service in Asp.net is described in three steps
    1.     Web.Config Settings.
    2.     Source Files for Logic.
    3.     Asp.net Pages to Implement.


    1.    Web.Config :

<configSections>               
<section name="ldapConfiguration" type="Application.Security.ActiveDirectoryConfiguration" allowLocation="true" allowDefinition="Everywhere"/>
</configSections>
<ldapConfiguration
enabled="true"
pageLevelSecurityCheck="false"
server="172.18.12.15:5000"
domain="DemoSite.local"
directoryPath="DC=DemoSite;DC=local"
groupName="elixtrauser" filter="(and(objectCategory=person)(objectClass=user)(samaccountname=usertosearch))" filterReplace="usertosearch"
adminUsername="administrator"
adminPassword="admin!#@" ADConnectionString="LDAP://172.18.12.15:5000/CN=Users;DC=DemoSite;DC=local" ></ldapConfiguration>

·         enabled: This enables active directory authentication process by registering "OnAuthenticate" event in page load of login page.
·         pageLevelSecurityCheck: This indicates if the user authentication check is needed in every page level or no.
·         server: LDAP server name or IP address
·         domain: Domain name
·         directoryPath: The path of the directory where the users reside.
·         groupName: Only the indicated user group will be able to login.
·         filter and filterReplace: Used to search user in the specified directory.


<membership defaultProvider="DemoSiteSqlMembershipProvider">
<providers>
<clear/>
<add
name="ADMembershipProvider"
type="Application.Security.ADMembershipProvider"
connectionStringName="ADConnectionString" connectionUsername="DemoSite.local\administrator"
connectionPassword=" admin!#@"
attributeMapUsername="sAMAccountName"/>
</providers>
</membership>


<roleManager enabled="true" defaultProvider="ActiveDirectoryRoleProvider">
<providers>
<clear/>
<add
name="ActiveDirectoryRoleProvider"
connectionStringName="ADConnectionString"
connectionUsername="administartor"
connectionPassword=" admin!#@"
attributeMapUsername="sAMAccountName" type="Application.Security.ActiveDirectoryRoleProvider"/>
</providers>
</roleManager>

<connectionStrings>
<clear /><add name="ADConnectionString" connectionString="LDAP://172.18.12.15:5000/CN=Users;DC=DemoSite;DC=local" /></connectionStrings> 

    2.    Application.Security(Source) :

    1.    Add a C# Class Library named Application.Security
    2.    Add Refrences for  System.DirectoryServices.Protocol, System.DirectoryServices.AccountManagement
    3.    Add these .cs files in it
I.              ActiveDirectoryHelper.cs
II.             ActiveDirectorySettings.cs
III.            ActiveDirectoryConfiguration.cs
IV.           ADMembershipDataProvider
V.            ActiveDirectoryRoleProvider
VI.           ADMembeshipController
VII.          ActiveDirectoryRoleController

Codes for Above .cs files are below.

I.              ActiveDirectoryHelper.cs

using System;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices;

namespace Application.Security
{
 public class ActiveDirectoryHelper
    {

        #region Helper Methods

        /// <summary>
        /// Gets the base principal context
        /// </summary>
        /// <returns>Retruns the PrincipalContext object</returns>
        public static PrincipalContext GetPrincipalContext()
        {
            try
            {
                PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain
                    , ActiveDirectorySettings.ActiveDirectorySettingsConfig.Domain
                    , ActiveDirectorySettings.ActiveDirectorySettingsConfig.DirectoryPath
                    , ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminUsername
                    , ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminPassword);
                return oPrincipalContext;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets the principal context on specified OU
        /// </summary>
        /// <param name="sOU">The OU you want your Principal Context to run on</param>
        /// <returns>Retruns the PrincipalContext object</returns>
        public static PrincipalContext GetPrincipalContext(string sOU)
        {
           // string ldapPath = "OU=Domain Users,DC=contoso,DC=com";
            string ldapPath = "OU=" + sOU + ";" +       ActiveDirectorySettings.ActiveDirectorySettingsConfig.DirectoryPath;          
            try
            {
                PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, ActiveDirectorySettings.ActiveDirectorySettingsConfig.Domain
                    , ldapPath, ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminUsername
                    , ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminPassword);
                return oPrincipalContext;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets the base DirectoryEntry
        /// </summary>     
        /// <returns>Retruns the DirectoryEntry object</returns>
        public static DirectoryEntry GetDirectoryEntry()
        {
         string domainAndUserName = ActiveDirectorySettings.ActiveDirectorySettingsConfig.Domain + @"\" + ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminUsername;
            try
            {
                DirectoryEntry oDirectoryEntry = new DirectoryEntry(ActiveDirectorySettings.ActiveDirectorySettingsConfig.ADConnectionString
                    , domainAndUserName, ActiveDirectorySettings.ActiveDirectorySettingsConfig.AdminPassword);
                return oDirectoryEntry;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #endregion

    }
}



II.            ActiveDirectorySettings.cs


using System.Configuration;

namespace Application.Security
{
  public static  class ActiveDirectorySettings
    {
   
        #region Member Variables
        //private static ActiveDirectoryConfiguration _currentActiveDirectoryConfiguration = null;
        #endregion

        #region Properties
        private static ActiveDirectoryConfiguration activeDirectorySettings = null;
     
        public static ActiveDirectoryConfiguration ActiveDirectorySettingsConfig
        {
            get
            {
                try
                {
                    if (activeDirectorySettings == null)
                    {
                        activeDirectorySettings = (ActiveDirectoryConfiguration)ConfigurationManager.GetSection("ldapConfiguration");                      
                    }
                }
                catch
                {
                }
                return activeDirectorySettings;
            }
        }    
      
     

        #endregion
    }
}


III.           ActiveDirectoryConfiguration.cs

using System;
using System.Configuration;

namespace Application.Security
{
    public class ActiveDirectoryConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("enabled", DefaultValue = "true", IsRequired = true)]
        public Boolean Enabled
        {
            get
            {
                return (Boolean)this["enabled"];
            }
            set
            {
                this["enabled"] = value;
            }
        }

        [ConfigurationProperty("server", DefaultValue = "", IsRequired = true)]
        public string Server
        {
            get
            {
                return this["server"].ToString();
            }

            set
            {
                this["server"] = value;
            }
        }

        [ConfigurationProperty("domain", DefaultValue = "", IsRequired = true)]
        public string Domain
        {
            get
            {
                return this["domain"].ToString();
            }

            set
            {
                this["domain"] = value;
            }
        }

        [ConfigurationProperty("directoryPath", DefaultValue = "", IsRequired = true)]
        public string DirectoryPath
        {
            get
            {
                return this["directoryPath"].ToString();
            }

            set
            {
                this["directoryPath"] = value;
            }
        }





        [ConfigurationProperty("groupName", DefaultValue = "", IsRequired = true)]
        public string GroupName
        {
            get
            {
                return this["groupName"].ToString();
            }

            set
            {
                this["groupName"] = value;
            }
        }

        [ConfigurationProperty("filter", DefaultValue = "", IsRequired = true)]
        public string Filter
        {
            get
            {
                return this["filter"].ToString();
            }

            set
            {
                this["filter"] = value;
            }
        }

        [ConfigurationProperty("filterReplace", DefaultValue = "", IsRequired = true)]
        public string FilterReplace
        {
            get
            {
                return this["filterReplace"].ToString();
            }

            set
            {
                this["filterReplace"] = value;
            }
        }

        [ConfigurationProperty("pageLevelSecurityCheck", DefaultValue = "false", IsRequired = true)]
        public Boolean PageLevelSecurityCheck
        {
            get
            {
                return (Boolean)this["pageLevelSecurityCheck"];
            }
            set
            {
                this["pageLevelSecurityCheck"] = value;
            }
        }

        [ConfigurationProperty("adminUsername", DefaultValue = "", IsRequired = true)]
        public string AdminUsername
        {
            get
            {
                return this["adminUsername"].ToString();
            }
            set
            {
                this["adminUsername"] = value;
            }
        }


        [ConfigurationProperty("adminPassword", DefaultValue = "", IsRequired = true)]
        public string AdminPassword
        {
            get
            {
                return this["adminPassword"].ToString();
            }
            set
            {
                this["adminPassword"] = value;
            }
        }
        [ConfigurationProperty("ADConnectionString", DefaultValue = "", IsRequired = true)]
        public string ADConnectionString
        {
            get
            {
                return this["ADConnectionString"].ToString();
            }
            set
            {
                this["ADConnectionString"] = value;
            }
        }
       


    }
}


IV.           ADMembershipDataProvider.cs

using System;
using Application.Security.Entities;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Collections;
using DemoSite.UserProfile;
using System.Collections.Generic;
using Application.Security.Helpers;

namespace Application.Security
{
    public static class ADMembershipDataProvider
    {         

        #region Validate Methods

        /// <summary>
        /// Validates the username and password of a given user
        /// </summary>
        /// <param name="sUserName">The username to validate</param>
        /// <param name="sPassword">The password of the username to validate</param>
        /// <returns>Returns True of user is valid</returns>
        public static bool ValidateCredentials(string sUserName, string sPassword)
        {
            try
            {
                PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                return oPrincipalContext.ValidateCredentials(sUserName, sPassword);
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Checks if the User Account is Expired
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Returns true if Expired</returns>
        public static bool IsUserExpired(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                if (oUserPrincipal.AccountExpirationDate != null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }



        /// <summary>
        /// Checks if user exsists on AD
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Returns true if username Exists</returns>
        public static bool IsUserExisiting(string sUserName)
        {
            try
            {
                if (GetUser(sUserName) == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Checks if user email accoung is  already exists
        /// </summary>
        /// <param name="email">The email to check</param>
        /// <returns>Retruns true of Account is locked</returns>
        public static bool IsUserEmailExists(string email)
        {
            try
            {
                DirectoryEntry entry = ActiveDirectoryHelper.GetDirectoryEntry();
                //Bind to the native AdsObject to force authentication.
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(mail=" + email + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Error authenticating userEmail. " + ex.Message);
            }

            return true;
        }

        /// <summary>
        /// Checks if user accoung is locked
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Retruns true of Account is locked</returns>
        public static bool IsAccountLocked(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                return oUserPrincipal.IsAccountLockedOut();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #endregion

        #region Search Methods

        /// <summary>
        /// Gets a certain user on Active Directory
        /// </summary>
        /// <param name="sUserName">The username to get</param>
        /// <returns>Returns the UserPrincipal Object</returns>
        public static UserPrincipal GetUser(string sUserName)
        {
            try
            {
                PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
                return oUserPrincipal;
            }
            catch (Exception ex)
            {

                throw ex;
            }


        }

        /// <summary>
        /// Gets a certain user on Active Directory
        /// </summary>
        /// <param name="roleName">seraching users in role</param>
        /// <param name="username">the username to get</param>
        /// <returns>Returns the UserPrincipal Object</returns>
        public static DemoSiteUserCollection SearchUsers(string roleName, string username)
        {
            try
            {
                DemoSiteUserCollection userColl = new DemoSiteUserCollection();
                List<UserInfo> users = new List<UserInfo>();

                PrincipalContext oPrincipal = ActiveDirectoryHelper.GetPrincipalContext();

                if (string.Empty != username.Trim())
                {
                    UserInfo obj = new UserInfo();
                    UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipal, username);
                    if (oUserPrincipal != null)
                    {
                        obj.UserID = oUserPrincipal.Guid.Value;
                        obj.UserName = oUserPrincipal.SamAccountName;
                        obj.FirstName = oUserPrincipal.GivenName;
                        obj.LastName = oUserPrincipal.Surname;
                        obj.Email = oUserPrincipal.EmailAddress;
                        obj.IsActive = oUserPrincipal.Enabled.Value;
                        users.Add(obj);
                    }
                }
                else
                {
                    GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, roleName);
                    if (gPrincipal != null)
                    {
                        foreach (Principal p in gPrincipal.GetMembers(false))
                        {
                            UserInfo obj = new UserInfo();
                            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipal, p.SamAccountName);
                            if (oUserPrincipal != null)
                            {
                                obj.UserID = oUserPrincipal.Guid.Value;
                                obj.UserName = oUserPrincipal.SamAccountName;
                                obj.FirstName = oUserPrincipal.GivenName;
                                obj.LastName = oUserPrincipal.Surname;
                                obj.Email = oUserPrincipal.EmailAddress;
                                obj.IsActive = oUserPrincipal.Enabled.Value;
                                users.Add(obj);
                            }
                        }
                    }
                }

                userColl.UserList = users;
                return userColl;

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// Gets all user on Active Directory located in a specific group
        /// </summary>      
        public static List<string> GetAllUsers(string sGroupName)
        {
            try
            {
                List<string> users = new List<string>();

                PrincipalContext oPrincipal = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, sGroupName);

                if (gPrincipal != null)
                {
                    foreach (Principal p in gPrincipal.GetMembers(false))
                    {
                        users.Add(p.DisplayName);
                    }
                }

                return users;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// Gets all groups on Active Directory
        /// </summary>      
        public static List<RoleInfo> GetAllGroups()
        {
            try
            {
                List<RoleInfo> AllGroups = new List<RoleInfo>();
                PrincipalContext ctx = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal qbeUser = new GroupPrincipal(ctx);
                Principal userOrGroup = qbeUser as Principal;
                userOrGroup.Name = "*";
                PrincipalSearcher searcher = new PrincipalSearcher(userOrGroup);

                // enumerate the results - you need to check what kind of principal you get back
                foreach (Principal found in searcher.FindAll())
                {
                    // is it a UserPrincipal - do what you need to do with that...
                    if (found is UserPrincipal)
                    {
                        //  ......                      
                    }
                    else if (found is GroupPrincipal)
                    {
                        RoleInfo obj = new RoleInfo();
                        obj.RoleName = found.Name;
                        obj.RoleID = found.Guid.Value;
                        AllGroups.Add(obj);
                    }
                }

                return AllGroups;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        /// <summary>
        /// Gets a certain group on Active Directory
        /// </summary>
        /// <param name="sGroupName">The group to get</param>
        /// <returns>Returns the GroupPrincipal Object</returns>
        public static GroupPrincipal GetGroup(string sGroupName)
        {
            try
            {
                PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
                return oGroupPrincipal;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets a list of the users Information
        /// </summary>
        /// <param name="sUserName">The user you want to get the Information</param>
        /// <returns>Returns an arraylist of userinformation</returns>
        public static UserProfileInfo GetProfile(string sUserName)
        {
            try
            {
                UserProfileInfo objinfo = new UserProfileInfo();
                PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
                if (oUserPrincipal != null)
                {
                    objinfo.FirstName = oUserPrincipal.GivenName;
                    objinfo.LastName = oUserPrincipal.Surname;
                    objinfo.Email = oUserPrincipal.EmailAddress;
                    objinfo.UserName = oUserPrincipal.SamAccountName;
                    objinfo.FullName = oUserPrincipal.DisplayName;
                    objinfo.ResPhone = oUserPrincipal.VoiceTelephoneNumber;
                    objinfo.AboutYou = oUserPrincipal.Description;

                }
                return objinfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #endregion

        #region User Account Methods

        /// <summary>
        /// Creates a new user on Active Directory
        /// </summary>
        /// <param name="obj">The UserInfo object hold userinformation</param>   
        /// <returns>returns the UserPrincipal object</returns>
        public static UserPrincipal CreateNewUser(UserInfo obj)
        {
            try
            {
                if (!IsUserExisiting(obj.UserName))
                {
                    PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();

                    UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, obj.UserName, obj.Password, true /*Enabled or not*/);

                    //User Log on Name  
                    if (oUserPrincipal != null)
                    {
                        oUserPrincipal.GivenName = obj.FirstName;
                        oUserPrincipal.Surname = obj.LastName;
                        oUserPrincipal.EmailAddress = obj.Email;
                        oUserPrincipal.Enabled = true;
                        oUserPrincipal.PasswordNeverExpires = false;
                        oUserPrincipal.SamAccountName = obj.UserName;
                        oUserPrincipal.DisplayName = obj.FirstName + " " + obj.LastName;
                        oUserPrincipal.UserPrincipalName = obj.UserName + "@" + ActiveDirectorySettings.ActiveDirectorySettingsConfig.Domain;
                        oUserPrincipal.Save();
                        string passwordchange;
                        SetUserPassword(obj.UserName, obj.Password, out passwordchange);
                    }
                    return oUserPrincipal;
                }
                else
                {
                    return GetUser(obj.UserName);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Update user Details
        /// </summary>
        /// <param name="obj">The UserInfo object hold userinformation</param>           
        public static UserPrincipal UpdateUser(UserProfileInfo obj)
        {
            try
            {
                PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, obj.UserName);
                //User Log on Name         
                if (oUserPrincipal != null)
                {
                    oUserPrincipal.GivenName = obj.FirstName;
                    oUserPrincipal.Surname = obj.LastName;
                    oUserPrincipal.EmailAddress = obj.Email;
                    oUserPrincipal.Enabled = true;
                    oUserPrincipal.PasswordNeverExpires = false;
                    oUserPrincipal.SamAccountName = obj.UserName;
                    oUserPrincipal.DisplayName = obj.FirstName + " " + obj.LastName;
                    oUserPrincipal.VoiceTelephoneNumber = obj.ResPhone;
                    oUserPrincipal.Description = obj.AboutYou;
                    oUserPrincipal.UserPrincipalName = obj.UserName + "@" + ActiveDirectorySettings.ActiveDirectorySettingsConfig.Domain;
                    oUserPrincipal.Save();
                }
                return oUserPrincipal;
            }
            catch (Exception ex)
            {
                throw ex;
            }



        }

        /// <summary>
        /// Sets the user password
        /// </summary>
        /// <param name="sUserName">The username to set</param>
        /// <param name="sNewPassword">The new password to use</param>
        /// <param name="sMessage">Any output messages</param>
        public static void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.SetPassword(sNewPassword);
                sMessage = "";
            }
            catch (Exception ex)
            {
                sMessage = ex.Message;
            }

        }

        /// <summary>
        /// Enables a disabled user account
        /// </summary>
        /// <param name="sUserName">The username to enable</param>
        public static void EnableUserAccount(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.Enabled = true;
                oUserPrincipal.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Force disbaling of a user account
        /// </summary>
        /// <param name="sUserName">The username to disable</param>
        public static void DisableUserAccount(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.Enabled = false;
                oUserPrincipal.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Force expire password of a user
        /// </summary>
        /// <param name="sUserName">The username to expire the password</param>
        public static void ExpireUserPassword(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.ExpirePasswordNow();
                oUserPrincipal.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }


        }

        /// <summary>
        /// Unlocks a locked user account
        /// </summary>
        /// <param name="sUserName">The username to unlock</param>
        public static void UnlockUserAccount(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.UnlockAccount();
                oUserPrincipal.Save();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Deletes a user in Active Directory
        /// </summary>
        /// <param name="sUserName">The username you want to delete</param>
        /// <returns>Returns true if successfully deleted</returns>
        public static bool DeleteUser(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.Delete();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #endregion

        #region Group Methods

        /// <summary>
        /// Creates a new group in Active Directory
        /// </summary>
        /// <param name="obj">The RoleInfo object holds all role information</param>
        /// <param name="status">The RoleCreationStatus object holds group existing informations</param>
        ///public GroupPrincipal CreateNewGroup(string sOU, string sGroupName, string sDescription, GroupScope oGroupScope, bool bSecurityGroup)      
        public static void CreateNewGroup(RoleInfo obj, out RoleCreationStatus status)
        {
            int ErrorCode = 0;
            //string sOU = "Builtin";
            try
            {
                if (!IsGroupExists(obj.RoleName))
                {
                    PrincipalContext oPrincipalContext = ActiveDirectoryHelper.GetPrincipalContext();
                    GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext, obj.RoleName);
                    if (oGroupPrincipal != null)
                    {                     
                        oGroupPrincipal.Name = obj.RoleName;
                        oGroupPrincipal.Description = "All " + obj.RoleName;
                        oGroupPrincipal.GroupScope = GroupScope.Global;
                        oGroupPrincipal.IsSecurityGroup = true;
                        oGroupPrincipal.Save();
                    }
                }
                else
                {
                    ErrorCode = 1;
                }
                switch (ErrorCode)
                {
                    case 1:
                        status = RoleCreationStatus.DUPLICATE_ROLE;
                        break;
                    default:
                        status = RoleCreationStatus.SUCCESS;
                        break;
                }              

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Adds the user for a given group
        /// </summary>
        /// <param name="sUserName">The user you want to add to a group</param>
        /// <param name="sGroupName">The group you want the user to be added in</param>
        /// <returns>Returns true if successful</returns>
        public static bool AddUserToGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    if (!IsUserGroupMember(sUserName, sGroupName))
                    {
                        oGroupPrincipal.Members.Add(oUserPrincipal);
                        oGroupPrincipal.Save();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Removes user from a given group
        /// </summary>
        /// <param name="sUserName">The user you want to remove from a group</param>
        /// <param name="sGroupName">The group you want the user to be removed from</param>
        /// <returns>Returns true if successful</returns>
        public static bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    if (IsUserGroupMember(sUserName, sGroupName))
                    {
                        oGroupPrincipal.Members.Remove(oUserPrincipal);
                        oGroupPrincipal.Save();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Checks if user is a member of a given group
        /// </summary>
        /// <param name="sUserName">The user you want to validate</param>
        /// <param name="sGroupName">The group you want to check the membership of the user</param>
        /// <returns>Returns true if user is a group member</returns>
        public static bool IsUserGroupMember(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    return oGroupPrincipal.Members.Contains(oUserPrincipal);
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets a list of the users group memberships
        /// </summary>
        /// <param name="sUserName">The user you want to get the group memberships</param>
        /// <returns>Returns an arraylist of group memberships</returns>
        public static ArrayList GetUserGroups(string sUserName)
        {
            try
            {
                ArrayList myItems = new ArrayList();
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
                foreach (Principal oResult in oPrincipalSearchResult)
                {
                    myItems.Add(oResult.Name);
                }
                return myItems;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets a list of the users authorization groups
        /// </summary>
        /// <param name="sUserName">The user you want to get authorization groups</param>
        /// <returns>Returns an arraylist of group authorization memberships</returns>
        public static ArrayList GetUserAuthorizationGroups(string sUserName)
        {
            try
            {
                ArrayList myItems = new ArrayList();
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetAuthorizationGroups();
                foreach (Principal oResult in oPrincipalSearchResult)
                {
                    myItems.Add(oResult.Name);
                }
                return myItems;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// Gets a list of the users authorization groups
        /// </summary>
        /// <param name="sGroupName">The group you want to get existing information</param>
        /// <returns>Returns true or false according group existance</returns>
        public static bool IsGroupExists(string sGroupName)
        {
            try
            {
                bool exists = false;

                PrincipalContext oPrincipal = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, sGroupName);

                if (gPrincipal != null)
                {
                    exists = true;
                }
                return exists;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        #endregion


    }
}


V.            ActiveDirectoryRoleProvider.cs

using System;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.Configuration;
using System.Globalization;
using System.DirectoryServices;
using System.Collections.Specialized;
using System.DirectoryServices.AccountManagement;
using System.Collections;
using Application.Security;


namespace Application.Security
{
    public class ActiveDirectoryRoleProvider : RoleProvider
    {      

        public override bool IsUserInRole(string username, string roleName)
        {
            string[] roles = GetRolesForUser(username);

            foreach (string role in roles)
            {
                if (role.Equals(roleName, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }

            return false;
        }

        public override string[] GetRolesForUser(string username)
        {
            try
            {
                var myItems = new List<string>();
                UserPrincipal oUserPrincipal = ADMembeshipController.GetUser(username);
                PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
                foreach (Principal oResult in oPrincipalSearchResult)
                {
                    myItems.Add(oResult.Name);
                }
                return myItems.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
           
        }             

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            try
            {
                var AllGroups = new List<string>();
                PrincipalContext ctx = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal qbeUser = new GroupPrincipal(ctx);
                Principal userOrGroup = qbeUser as Principal;
                userOrGroup.Name = "*";
                PrincipalSearcher searcher = new PrincipalSearcher(userOrGroup);              

                // enumerate the results - you need to check what kind of principal you get back
                foreach (Principal found in searcher.FindAll())
                {
                    // is it a UserPrincipal - do what you need to do with that...
                    if (found is UserPrincipal)
                    {
                        //  ......

                    }
                    else if (found is GroupPrincipal)
                    {
                        AllGroups.Add(found.Name);

                    }
                }

                return AllGroups.ToArray();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }             

        public override string[] GetUsersInRole(string roleName)
        {
            try
            {
                List<string> users = new List<string>();

                PrincipalContext oPrincipal = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, roleName);

                if (gPrincipal != null)
                {
                    foreach (Principal p in gPrincipal.GetMembers(false))
                    {
                        users.Add(p.DisplayName);
                    }
                }

                return users.ToArray();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }      

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            try
            {
                bool exists = false;

                PrincipalContext oPrincipal = ActiveDirectoryHelper.GetPrincipalContext();
                GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, roleName);

                if (gPrincipal != null)
                {
                    exists = true;
                }
               return exists;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

    }
}


VI.           ADMembeshipController.cs

using System.DirectoryServices.AccountManagement;
using System.Collections;
using DemoSite.UserProfile;
using System.Collections.Generic;
using Application.Security.Helpers;

namespace Application.Security
{
 public static  class ADMembeshipController
    {

        #region Validate Methods
      
        public static bool ValidateCredentials(string sUserName, string sPassword)
        {
            return ADMembershipDataProvider.ValidateCredentials(sUserName,sPassword);
          
        }      
        public static bool IsUserExpired(string sUserName)
        {
            return ADMembershipDataProvider.IsUserExpired(sUserName);          
        }
           
        public static bool IsUserExisiting(string sUserName)
        {
         return ADMembershipDataProvider.IsUserExisiting(sUserName);
          
        }     
        public static bool IsUserEmailExists(string email)
        {
            return ADMembershipDataProvider.IsUserEmailExists(email);
          
        }
     
        public static bool IsAccountLocked(string sUserName)
        {
            return ADMembershipDataProvider.IsAccountLocked(sUserName);
          
        }
        #endregion

        #region Search Methods      
        public static UserPrincipal GetUser(string sUserName)
        {
            return ADMembershipDataProvider.GetUser(sUserName);
         
        }
        public static DemoSiteUserCollection SearchUsers(string roleName, string username)
        {
            return ADMembershipDataProvider.SearchUsers(roleName, username);
        }
        public static List<string> GetAllUsers(string sGroupName)
        {
            return ADMembershipDataProvider.GetAllUsers(sGroupName);
        }
        public static List<RoleInfo> GetAllGroups()
        {
            return ADMembershipDataProvider.GetAllGroups();
        }
      
        public static GroupPrincipal GetGroup(string sGroupName)
        {
            return ADMembershipDataProvider.GetGroup(sGroupName);
        }
        public static UserProfileInfo GetProfile(string sUserName)
        {
            UserProfileInfo objinfo = new UserProfileInfo();
            objinfo = ADMembershipDataProvider.GetProfile(sUserName);
            return objinfo;
        }

        #endregion

        #region User Account Methods
     
        public static UserPrincipal CreateNewUser(UserInfo obj)
        {
            return ADMembershipDataProvider.CreateNewUser(obj);  
        }
        public static UserPrincipal UpdateUser(UserProfileInfo obj)
        {
            return ADMembershipDataProvider.UpdateUser(obj);
        }
          
        public static void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
        {
           ADMembershipDataProvider.SetUserPassword(sUserName,sNewPassword, out sMessage);  

        }

        public static void EnableUserAccount(string sUserName)
        {
            ADMembershipDataProvider.EnableUserAccount(sUserName);  
        }
      
        public static void DisableUserAccount(string sUserName)
        {
            ADMembershipDataProvider.DisableUserAccount(sUserName);  
        }
      
        public static void ExpireUserPassword(string sUserName)
        {
            ADMembershipDataProvider.ExpireUserPassword(sUserName);  

        }
      
        public static void UnlockUserAccount(string sUserName)
        {
            ADMembershipDataProvider.UnlockUserAccount(sUserName);  
        }

        public static bool DeleteUser(string sUserName)
        {
            return ADMembershipDataProvider.DeleteUser(sUserName);  
        }

        #endregion

        #region Group Methods    
  
        public static void CreateNewGroup(RoleInfo obj, out RoleCreationStatus status)
        {
            ADMembershipDataProvider.CreateNewGroup(obj, out status);  
        }

        public static bool AddUserToGroup(string sUserName, string sGroupName)
        {
            return ADMembershipDataProvider.AddUserToGroup(sUserName, sGroupName); 
        }

        public static bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            return ADMembershipDataProvider.RemoveUserFromGroup(sUserName, sGroupName); 
        }
      
        public static bool IsUserGroupMember(string sUserName, string sGroupName)
        {
            return ADMembershipDataProvider.IsUserGroupMember(sUserName, sGroupName); 
        }

        public static ArrayList GetUserGroups(string sUserName)
        {
            return ADMembershipDataProvider.GetUserGroups(sUserName); 
        }

        public static ArrayList GetUserAuthorizationGroups(string sUserName)
        {
            return ADMembershipDataProvider.GetUserAuthorizationGroups(sUserName); 
        }
        public static bool IsGroupExists(string sGroupName)
        {
            return ADMembershipDataProvider.IsGroupExists(sGroupName); 
        }

        #endregion

        #region Helper Methods

        public static PrincipalContext GetPrincipalContext()
        {
            return ActiveDirectoryHelper.GetPrincipalContext();
        }

        public static PrincipalContext GetPrincipalContext(string sOU)
        {
            return ActiveDirectoryHelper.GetPrincipalContext(sOU);
        }

        #endregion


    }
}



VII.         ActiveDirectoryRoleController.cs

using System;
using Application.Security.Entities;

namespace Application.Security
{
 public  class ActiveDirectoryRoleController:ActiveDirectoryRoleProvider
    {
    
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            ActiveDirectoryRoleProvider rp = new ActiveDirectoryRoleProvider();
            return rp.GetAllRoles();
        }

        public override string[] GetRolesForUser(string username)
        {
            ActiveDirectoryRoleProvider rp = new ActiveDirectoryRoleProvider();
            return (rp.GetRolesForUser(username));
           // throw new NotImplementedException();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            ActiveDirectoryRoleProvider rp = new ActiveDirectoryRoleProvider();
            return (rp.GetUsersInRole(roleName));
        }
        
        public override bool IsUserInRole(string username, string roleName)
        {
            throw new NotImplementedException();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }

    }
}


    3.     Login.aspx.cs (Asp.net Page)

if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(Password.Text)))
            {             
                if (true == ADMembeshipController.IsUserExisiting(UserName.Text))
                {                  
                    if (true == ADMembeshipController.ValidateCredentials(UserName.Text, Password.Text))
                    {
                         //SucessFullLogin(user);
                    }
                 }
            }

Note:
Doing this you can face connection permission exceptions like
Principal Server Down Exception, The server could not be contacted.

For this configure your DNS in remote and resolve the IP Address of your computer