Common.Net library methods: Querying Active Directory for users and groups

Finding the groups a user belongs to in active directory along with the members of that group is something that comes up a lot when .Net apps use Active Directory for authentication. Here are some common library methods to find members of a group or groups a member belongs to. This code requires a reference to System.DirectoryServices.AccountManagement.
    using System;
    using System.Collections.Generic;
    using System.DirectoryServices.AccountManagement;
    using System.Linq; 

    public class ActiveDirectoryGateway 
    {
        private readonly string domain;

        private readonly ContextType contextType;

        public ActiveDirectoryGateway(ContextType contextType, string domain)
        {
            this.contextType = contextType;
            this.domain = domain;
        }

        /// <summary>
        /// Retrieves a list of AD groups belonging to an AD User.
        /// </summary>
        /// <param name="user">The active directory user.</param>
        /// <returns>A list of AD groups the user belongs to.</returns>
        public virtual IEnumerable<string> FindGroups(string user)
        {
            var list = new List<string>();
            using (var context = new PrincipalContext(this.contextType, this.domain))
            {
                using (var userPrincipal = UserPrincipal.FindByIdentity(context, user))
                {
                    if (userPrincipal == null)
                    {
                        return list;
                    }

                    using (var results = userPrincipal.GetGroups())
                    {
                        list.AddRange(results.Select(result => result.Name));
                    }
                }
            }

            list.Sort();
            return list;
        }

        /// <summary>
        /// Lists members of group.
        /// </summary>
        /// <param name="grp">The AD group.</param>
        /// <returns>A list of AD members of the group.</returns>
        public virtual IEnumerable<string> FindMembersOfGroup(string grp)
        {
            var list = new List<string>();
            using (var context = new PrincipalContext(this.contextType, this.domain))
            {
                using (var group = GroupPrincipal.FindByIdentity(context, grp))
                {
                    if (group == null)
                    {
                        return list;
                    }

                    list.AddRange(group.GetMembers(true).Select(result => result.Name));
                }
            }

            return list;
        }
}

Comments

Popular posts from this blog

AutoItX4Java - Java AutoIt Bridge

The SQL Server and .Net equivalent of PHP and MySQL's SHA1 function

Automated web testing with Java, Selenium RC, LoggingSelenium, HtmlUnit and TestNG