Check Active directory user using C#


Check user existence in Active Directory


        public bool DoesUserExist(string userName, string domain)
        {
            try
            {
                using (var domainContext = new PrincipalContext(ContextType.Domain, domain))
                {
                    using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
                    {
                        return foundUser != null;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
     

Validate user against Active Directory


 public void  UserExists(string domainname, string userName, string Password)
        {
            try
            {
                string ldapPath = LDapUrl;// path of directory
                DirectoryEntry directionEntry = new DirectoryEntry(ldapPath, domainname + "\\" + userName, Password);
                if (directionEntry != null)
                {
                    DirectorySearcher search = new DirectorySearcher(directionEntry);
                    search.Filter = "(SAMAccountName=" + userName + ")";
                    SearchResult result = search.FindOne();
                    if (result != null)
                    {
                     
                        Response.Redirect(http;//www.google.com, false)
                    }

                }
            }
            catch (DirectoryServicesCOMException ex)
            {

              ex.Message;
            }

        }

No comments:

Post a Comment