Tuesday, 23 February 2010

Query Active Directory for list of roles (.NET 3.5)

Here is a snippet of code to retrieve a list of roles for a user in .NET 3.5. This code uses the System.DirectoryServices.AccountManagement namespace which is exclusive to 3.5.

        /// <summary>
        /// Retrieve listing of all roles to which a specified user belongs.
        /// </summary>
        /// <param name="identity">Current Windows Identity</param>
        /// <returns>String array of roles</returns>
        public string[] GetRolesForUser(IIdentity identity)
        {
            //Create an ArrayList to store our resultant list of groups.
            ArrayList results = new ArrayList();
 
            //PrincipalContext encapsulates the server or domain against which all operations are performed.
            using (PrincipalContext context = new PrincipalContext(ContextType.Domain, null, "NORTHWAVE"))
            {
                try
                {
                    //Create a referance to the user account we are querying against.
                    UserPrincipal p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, identity.Name);
                    
                    //Get the user's security groups.  This is necessary to return nested groups, but will NOT return distribution groups.
                    var groups = p.GetGroups();
                    
                    foreach (GroupPrincipal group in groups)
                    {
                        results.Add(group.SamAccountName);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
 
            return results.ToArray(typeof(String)) as String[];
        }

No comments: