Check If Active Directory User is in Group C# ASP .Net

When searching initially for the above (title of my blog ^), I initially found no good apparent solutions. It was off to the drawing board!

LDAP – lightweight directory access protocol. Defines a syntax and tools for querying and enumerating access levels, groups and users associated with an active directory domain.

If you are a .Net developer or system admin on any system, you will likely encounter LDAP as well as other similar protocols and discover a learning curve with each.

See references below for other quick examples that may be helpful in the future.

ASP.Net (check if user has access to site based on AD group permissions):

public static string username {
        get {
            return HttpContext.Current.Request.ServerVariables["AUTH_USER"];
        }
        }
        public static string usergroup;
        public static string user_firstname;

        /// <summary>
        /// Check if current user browsing site is logged in.
        /// </summary>
        public static bool IsLoggedIn
        {
            get
            {
                //currently using AD

                if (HttpContext.Current.Session["IsLoggedIn"] != null)
                {
                    return (bool)HttpContext.Current.Session["IsLoggedIn"];
                }

                string loginname = ExtractUserName(username);

                DirectorySearcher search = new DirectorySearcher("LDAP://RUSSWHITNEY");
                //search.Filter = String.Format("(cn={0})", loginname);
                //search.Filter = String.Format("(&(cn={0})(SAMAccountName={1}))", "Direct Mail Admin", loginname);
                search.Filter = String.Format("(SAMAccountName={0})", loginname);
                //search.Filter = "(&(objectClass=group)(cn=" + "Direct Mail Admin" + "))";
                search.PropertiesToLoad.Add("memberOf");
                search.PropertiesToLoad.Add("givenName");
                System.Text.StringBuilder groupsList = new System.Text.StringBuilder();

                SearchResult result = search.FindOne();

                bool returnvalue = false;

                if (result.Properties["memberOf"].Count > 0)
                {
                    foreach (string prop in result.Properties["memberOf"])
                    {
                        if (prop.ToLower().Contains("cn=groupname one"))
                        {
                            utils.usergroup = "admin";

                            if (result.Properties["givenName"].Count > 0)
                            {
                                user_firstname = result.Properties["givenName"][0].ToString();
                            }


                            returnvalue = true;
                        }
                        else if (prop.ToLower().Contains("cn=groupname two"))
                        {
                            utils.usergroup = "user";

                            if (result.Properties["givenName"].Count > 0)
                            {
                                user_firstname = result.Properties["givenName"][0].ToString();
                            }

                            returnvalue = true;
                        }
                    }

                    //returnvalue = false;  //if empty or doesnt contain above stays as false from initialization
                }
                else
                {
                    returnvalue = false;
                }

                if (HttpContext.Current.Session["IsLoggedIn"] == null)
                {
                    HttpContext.Current.Session.Add("IsLoggedIn", returnvalue);
                }
                else
                {
                    HttpContext.Current.Session["IsLoggedIn"] = returnvalue;
                }
                return returnvalue;
            }
        }

        #region "Active Directory"

        /// <summary>
        /// 
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        static bool IsExistInAD(string loginName)
        {
            string userName = ExtractUserName(loginName);
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(SAMAccountName={0})", userName);
            search.PropertiesToLoad.Add("cn");
            SearchResult result = search.FindOne();

            if (result == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        static string ExtractUserName(string path)
        {
            string[] userPath = path.Split(new char[] { '\\' });
            return userPath[userPath.Length - 1];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        static string GetADUserGroups(string userName)
        {
            DirectorySearcher search = new DirectorySearcher();
            search.Filter = String.Format("(cn={0})", userName);
            search.PropertiesToLoad.Add("memberOf");
            System.Text.StringBuilder groupsList = new System.Text.StringBuilder();

            SearchResult result = search.FindOne();
            if (result != null)
            {
                int groupCount = result.Properties["memberOf"].Count;

                for (int counter = 0; counter < groupCount; counter++)
                {
                    groupsList.Append((string)result.Properties["memberOf"][counter]);
                    groupsList.Append("|");
                }
            }
            groupsList.Length -= 1; //remove the last '|' symbol

            return groupsList.ToString();
        }
        #endregion


Note:
Any snippets may have been condensed from their original sources for brevity. See references for original articles.

All server side code examples are in C# .Net.

References
Wikipedia, “LDAP”, http://en.wikipedia.org/wiki/LDAP
Wikipedia, AD, http://en.wikipedia.org/wiki/Active_Directory
StackOverflow, http://stackoverflow.com/questions/637486/how-to-get-the-current-users-active-directory-details-in-c
MSDN, http://msdn.microsoft.com/en-us/library/aa746475%28v=vs.85%29.aspx
CentOS, http://www.centos.org/docs/5/html/CDS/ag/8.0/Finding_Directory_Entries-Using_ldapsearch.html
Justskins, http://www.justskins.com/forums/active-directory-search-fails-84700.html
Weblogs, http://weblogs.asp.net/steveschofield/archive/2004/04/28/121857.aspx

About these ads

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on February 11, 2011, in Programming & Development and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink. 2 Comments.

  1. What is the istructions?

    utils.usergroup = “user”;

    utils.usergroup = “admin”;

    In my VS don’t exist it.

    • The entire code block you see here is inside a static “utils” class. “usergroup” is simply a string value in this class which you can see at the top of this code block. This variable is used to store the group returned from the AD query for use elsewhere throughout the app.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: