0

I am trying to implement a ChangePassword functionality on ActiveDirectory through the UserPrincipal. The code looks like this:

        using System.DirectoryServices.AccountManagement;

        private PrincipalContext Context { get; set; }

        ...
        Context = new PrincipalContext(ContextType.Domain,
            AdDomain,
            AdRoot,
            ContextOptions.SimpleBind,
            AdUsername,
            AdPassword)
        ...

        public bool ChangePassword(string login, string password, string newPassword, out string message)
        {
            using (var foundUser = UserPrincipal.FindByIdentity(Context, IdentityType.SamAccountName, login))
            {
                try
                {
                    foundUser.ChangePassword(password, newPassword);
                    foundUser.Save();
                }
                catch (Exception e)
                {
                    message = e.Message;
                    return false;
                }

                return true;
            }
        }

When I try to test this on my Windows 10 machine I get an exception on ChangePassword, System.Runtime.InteropServices.COMException - One or more input parameters are invalid.

However, when I run this exact same code in the same project while connecting to the same AD domain on my Windows 7 machine it runs without error and changes the password. What could be causing this different behavior on the environments, and why does that error happen?

R. Yu
  • 1
  • 2
  • http://stackoverflow.com/questions/33717673/system-directoryservices-accountmanagement-principalcontext-broken-after-windows Take a look here. – Lorenzo Grossi Oct 05 '16 at 15:40
  • I've made the registry changes with RegisteredOwner and RegisteredOrganization on the Windows 10 machine, but that did not solve this error. – R. Yu Oct 05 '16 at 15:49

1 Answers1

0

When the Context is created, make sure to set the ContextOptions to ContextOptions.Negotiate . If you have mentioned ContextOptions.SimpleBind SetPassword may not work.

PrincipalContext oPrincipalContext = new PrincipalContext
               (ContextType.Domain, "Name", "DefaultOU(if required)", ContextOptions.Negotiate,
               "Service Account(if required)", "Service password");
Rohit Poudel
  • 1,793
  • 2
  • 20
  • 24