更改密码Windows AD C#

更改密码Windows AD C#,c#,windows,active-directory,passwords,impersonation,C#,Windows,Active Directory,Passwords,Impersonation,下面是我正在使用的代码:即使我使用Administrators组中的帐户进行模拟,我也会被拒绝访问 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 ca

下面是我正在使用的代码:即使我使用Administrators组中的帐户进行模拟,我也会被拒绝访问

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

这周的模仿是怎么回事?
PrincipalContext
对象有一个接受用户凭据的构造函数。您需要做的只是:

PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, username, password);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);
up.SetPassword(txtNewChangedPassword.Text);

这周的模仿是怎么回事?
PrincipalContext
对象有一个接受用户凭据的构造函数。您需要做的只是:

PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain, username, password);
UserPrincipal up = UserPrincipal.FindByIdentity(pc, username);
up.SetPassword(txtNewChangedPassword.Text);

SetPassword
要求您的代码正在运行的用户是Active Directory中的管理员。由于您已有可用的旧密码,请尝试替换此行:

up.SetPassword(txtNewChangedPassword.Text);
为此:

up.ChangePassword(password, txtNewChangedPassword.Text);
up.Save();

SetPassword
要求您的代码正在运行的用户是Active Directory中的管理员。由于您已有可用的旧密码,请尝试替换此行:

up.SetPassword(txtNewChangedPassword.Text);
为此:

up.ChangePassword(password, txtNewChangedPassword.Text);
up.Save();

我仍然被“拒绝访问”然后,您指定的用户没有更改用户密码的权限,或者新密码不符合Active Directory中定义的要求。用户有权限,并且我试图更改的密码在我通过UIS执行操作时有效。用户是否有更改密码的权限并不重要,除非他们也是用户使用
SetPassword
时AD中的管理员;请使用带有
SetPassword
的管理员广告帐户,或者查看我的答案,以了解更改用户广告密码的其他方法。我仍然收到“拒绝访问”的消息然后,您指定的用户没有更改用户密码的权限,或者新密码不符合Active Directory中定义的要求。用户有权限,并且我试图更改的密码在我通过UIS执行操作时有效。用户是否有更改密码的权限并不重要,除非他们也是用户使用
SetPassword
时AD中的管理员;使用带有
SetPassword
的管理员广告帐户,或者查看我的答案,以了解更改用户广告密码的其他方法。