Click here to Skip to main content
15,884,720 members
Articles / Web Development / ASP.NET

Bypass Forms Authentication to Use Active Directory User Authentication in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.88/5 (13 votes)
9 Oct 2011CPOL2 min read 79K   3.6K   47  
This article describes how to keep form based and active directory user based authentication process in parallel in ASP.NET.
using System;
using System.Diagnostics;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.Web;
using System.Web.Security;
using System.Configuration;

namespace ActiveDirectoryAuthentication.Helper
{
    public static class ActiveDirectoryConnector
    {
        #region Member Variables
        
        private static ActiveDirectoryConfiguration _currentActiveDirectoryConfiguration = null;

        #endregion

        #region Properties

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

        #endregion

        #region Methods

        public static bool IsUserLoggedIn(string userName, string password)
        {
            try
            {
                if (ActiveDirectorySettings.Enabled)
                {
                    int startIndex = userName.IndexOf("@");
                    if (startIndex >= 0)
                    {
                        userName = userName.Substring(0, startIndex);
                    }
                    DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://" + ActiveDirectorySettings.Server + "/" + ActiveDirectorySettings.DirectoryPath, userName, password);
                    DirectorySearcher searcher = new DirectorySearcher(ldapConnection);
                    searcher.Filter = ActiveDirectorySettings.Filter.Replace("and", "&");
                    searcher.Filter = searcher.Filter.Replace(ActiveDirectorySettings.FilterReplace, userName);
                    searcher.PropertiesToLoad.Add("memberOf");
                    searcher.PropertiesToLoad.Add("userAccountControl");

                    SearchResult directoryUser = searcher.FindOne();
                    if (directoryUser != null)
                    {
                        int flags = Convert.ToInt32(directoryUser.Properties["userAccountControl"][0].ToString());
                        if (!Convert.ToBoolean(flags & 0x0002))
                        {
                            string desiredGroupName = ActiveDirectorySettings.GroupName.ToLower();
                            if (desiredGroupName!=string.Empty)
                            {
                                desiredGroupName = "cn=" + desiredGroupName + ",";
                                int numberOfGroups = directoryUser.Properties["memberOf"].Count;
                                bool isWithinGroup = false;
                                for (int i = 0; i < numberOfGroups; i++)
                                {
                                    string groupName = directoryUser.Properties["memberOf"][i].ToString().ToLower();
                                    if (groupName.Contains(desiredGroupName))
                                    {
                                        isWithinGroup = true;
                                        break;
                                    }
                                }
                                if (!isWithinGroup)
                                {
                                    throw new Exception("User [" + userName + "] is not a member of the desired group.");
                                }
                            }
                            return true;
                        }
                        else
                        {
                            throw new Exception("User [" + userName + "] is inactive.");
                        }
                    }
                    else
                    {
                        throw new Exception("User [" + userName + "] not found in the specified active directory path.");
                    }
                }
                else
                {
                    return true;
                }
            }
            catch (LdapException ex)
            {
                if (ex.ErrorCode == 49)
                {
                    throw new Exception("Invalid user authentication. Please input a valid user name & pasword and try again.",ex);
                }
                else
                {
                    throw new Exception("Active directory server not found.", ex);
                }
            }
            catch (DirectoryOperationException ex)
            {
                throw new Exception("Invalid active directory path.", ex);
            }
            catch (DirectoryServicesCOMException ex)
            {
                if (ex.ExtendedError == 8333)
                {
                    throw new Exception("Invalid active directory path.", ex);
                }
                else
                {
                    throw new Exception("Invalid user authentication. Please input a valid user name & pasword and try again.", ex);
                }
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                throw new Exception("Active directory server not found.", ex);
            }
            catch (ArgumentException ex)
            {
                if (ex.Source == "System.DirectoryServices")
                {
                    throw new Exception("Invalid search filter expression.", ex);
                }
                else
                {
                    throw new Exception("Unhandeled exception occured while authenticating user using active directory.", ex);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unhandeled exception occured while authenticating user using active directory.", ex);
            }
        }

        public static void UserAuthenticationCheck()
        {
            try
            {
                if (ActiveDirectorySettings.Enabled)
                {
                    if ((ActiveDirectorySettings.PageLevelSecurityCheck) && !HttpContext.Current.Request.Url.AbsolutePath.ToLower().Contains("login.aspx"))
                    {
                        if (HttpContext.Current.User != null)
                        {
                            if (HttpContext.Current.User.Identity.IsAuthenticated)
                            {
                                if (HttpContext.Current.User.Identity is FormsIdentity)
                                {
                                    FormsIdentity formIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
                                    FormsAuthenticationTicket userAuthTicket = formIdentity.Ticket;
                                    if (!IsUserLoggedIn(userAuthTicket.Name, userAuthTicket.UserData))
                                    {
                                        FormsAuthentication.SignOut();
                                        FormsAuthentication.RedirectToLoginPage();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
            }
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Ominto Inc
United Arab Emirates United Arab Emirates
I am Bachelor in CSE from Khulna University of Engineering & Technology,Bangladesh. I have more than 11 years experience in software design & development, data analysis & modeling, project management and currently working in a software company in Dubai,UAE as a Lead Software Engineer. I am MCAD(Microsoft Certified Application Developer) certified since 2005. Please feel free to contact with me at nill_akash_7@yahoo.com.


Comments and Discussions