Search code examples
c#windowsactive-directorypasswordsimpersonation

Change Password Windows AD C#


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);
}

Solution

  • 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();