Change Password Windows AD C#

3.1k views Asked by At

Below is the code I am using: I get an access denied even though I am impersonating with an account that is in the Administrators group.

SafeTokenHandle safeTokenHandle;
string userName, domainName;
// Get the user token for the specified user, domain, and password using the 
// unmanaged LogonUser method. 
// The local machine name can be used for the domain name to impersonate a user on this machine.


const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token. 
const int LOGON32_LOGON_INTERACTIVE = 2;

// Call LogonUser to obtain a handle to an access token. 
bool returnValue = LogonUser(username, domain, password,
LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out safeTokenHandle);

if (false == returnValue)
{
    int ret = Marshal.GetLastWin32Error();
}
using (safeTokenHandle)
{
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(safeTokenHandle.DangerousGetHandle()))
{
string x = WindowsIdentity.GetCurrent().Name;
PrincipalContext pc = new PrincipalContext(ContextType.Domain);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);
up.SetPassword(txtNewChangedPassword.Text);
}
3

There are 3 answers

0
areyling On BEST ANSWER

SetPassword requires the user your code is running as to be an admin in Active Directory. Since you already have the old password available, try replacing this line:

up.SetPassword(txtNewChangedPassword.Text);

With this:

up.ChangePassword(password, txtNewChangedPassword.Text);
up.Save();
5
Ashigore On

What is it with impersonation this week? The PrincipalContext object has a constructor that accepts user credentials. All you need to do is:

PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, username, password);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);
up.SetPassword(txtNewChangedPassword.Text);
0
user2724949 On
            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, username, password))
            {
                //PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, username, password);
                UserPrincipal up = new UserPrincipal(pc);
                up.SetPassword(newPassword);
            }