Reputation: 765
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);
}
Upvotes: 1
Views: 3252
Reputation: 11
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);
}
Upvotes: 1
Reputation: 2191
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();
Upvotes: 4
Reputation: 4678
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);
Upvotes: 1