Return to Snippet

Revision: 25764
at April 8, 2010 15:44 by victorboba


Initial Code
public static bool IsUserInDomain(string userName)
        {
            string name = userName;
            bool isInDomain = false;
            if (name.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) != -1)
                name = name.Substring(name.IndexOf(@"\", StringComparison.OrdinalIgnoreCase) + 1);

            string ADpath = System.Configuration.ConfigurationManager.AppSettings["ADPath"];
            string ADusername = System.Configuration.ConfigurationManager.AppSettings["ADUser"];
            string ADpassword = System.Configuration.ConfigurationManager.AppSettings["ADPassword"];
            string securityGroup = System.Configuration.ConfigurationManager.AppSettings["ADSecurityGroup"];

            DirectoryEntry de = new DirectoryEntry { Path = ADpath, Username = ADusername, Password = ADpassword };

            DirectorySearcher searcher = new DirectorySearcher(de);
            // "!userAccountControl:1.2.840.113556.1.4.803:=2"  is a check for enabled users only
            searcher.Filter = "(&(&((objectClass=user)(objectClass=person))(sAMAccountName=" + userName + ")(!userAccountControl:1.2.840.113556.1.4.803:=2)))";

            // Is the user found?
            SearchResult sr = searcher.FindOne();
            if (sr != null)
            {
                // Find the Security group
                searcher = new DirectorySearcher(de);
                searcher.Filter = "(&(objectCategory=group)(sAMAccountName=" + securityGroup + "))";
                searcher.PropertiesToLoad.Add("distinguishedname");

                foreach (SearchResult item in searcher.FindAll())
                {
                    // Get the DN from the group
                    if (item.Properties["distinguishedname"].Count > 0)
                    {
                        String dn = item.Properties["distinguishedname"][0].ToString();
                        searcher = new DirectorySearcher(de);
                        searcher.Filter = "(&(sAMAccountName=" + userName + ")(memberOf=" + dn + "))";
                        SearchResult userAndSecurityGroup = searcher.FindOne();
                        if (userAndSecurityGroup != null)
                        {
                            isInDomain = true;
                            break;
                        }
                    }
                }
            }

            return isInDomain;
        }

Initial URL

                                

Initial Description

                                

Initial Title
Validate username and security group in Active Directory

Initial Tags
directory

Initial Language
C#