Wednesday, August 11, 2010

Changing domain password Programmatically

I was writing a web utility to change the domain password of the user. Here, the user required to enter the current password and the new password.


First error I was encountered - "The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements. (Exception from HRESULT: 0x800708C5)"


Initially I thought that, there is a problem in password strength, so I try may combinations to create the most complex password in the world! But getting the same error.


After doing some research on the internet I found that, "Minimum Password Age" setting needs to set to 0, to allow users set the password many times a day. The default value is 1.





Following are the code snippet used for changing password:

               string Username = strAccountName.Substring(strAccountName.LastIndexOf(@"\") + 1); //Getting account name from the parent application, "Rocky\\Soumyendra"
                string newpwd = txtNewPass.Text;
                string oldpwd = txtOldPass.Text;

                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    PrincipalContext principalContext = null;
                    principalContext = new PrincipalContext(ContextType.Domain, domain);
                 
                    UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, Username);

                    if (user != null)
                    {

                        user.ChangePassword(oldpwd, newpwd);
                        user.Enabled = true;//By default User is Disabled in Domain
                        user.Save();

                    }
                });
                SendEmail(newpwd);




No comments: