Friday, 7 March 2014

Change Active Directory Password C#


Any company which uses SharePoint , there is always a need for the User where they can change their AD password and change the password to something which they easily remember.

But changing the AD password is not that easy and there are certain restriction on this, as each Company has its own policies. Here, we will discuss how we can change AD password using .NET/C#.


There are two sets of .NET classes that can be used to change AD password.
2. System.DirectoryServices.AccountManagement

I have found the first approach as the best and easy to use, although it is obsolete.


        protected void Change_AD_Password(string serviceAccntName, string serviceAccntPass, string userName,string newPassWord )
                //the LDAP server path, it can be an IP Address of the server or web-address anything
                string _path = "LDAP://,DC=net";

                //We are using service account to authenticate to LDAP server and only service account will have the rights to change AD password
                System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry(_path, serviceAccntName, serviceAccntPass);

                System.DirectoryServices.DirectorySearcher mySearcher = new System.DirectoryServices.DirectorySearcher(entry);
                mySearcher.Filter = ("(objectClass=User)");
                SortOption option = new SortOption("Mail", System.DirectoryServices.SortDirection.Ascending);
                mySearcher.Sort = option;

                foreach (System.DirectoryServices.SearchResult resEnt in mySearcher.FindAll())
                    System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();

                    //the user whose password needs to be changes
                    if (de.Properties["sAMAccountName"].Value.ToString().ToLower() == userName.ToLower())
                        de.Invoke("SetPassword", new object[] {newPassWord });
            catch (Exception ex)
              throw ex;


Points to Remember:
1. Password must follow the password policy remember it (like no. of characters, how many times a user can change the password, new password should not be from the old password). Consult the admin and check the password policy.
2. There is an Admin settings which disables the user to change AD Password.(when we go to AD server open the user properties , we can see a check-box which says User can't change their password)
3. The application pool should be given permission to access LDAP server.