更改密码Windows AD C#

时间:2015-06-23 18:34:05

标签: c# windows active-directory passwords impersonation

以下是我正在使用的代码:即使我冒充管理员组中的帐户,我也会拒绝访问。

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 个答案:

答案 0 :(得分:3)

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

up.SetPassword(txtNewChangedPassword.Text);

有了这个:

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

答案 1 :(得分:0)

本周假冒是什么意思? PrincipalContext对象具有接受用户凭据的构造函数。您所需要做的就是:

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

答案 2 :(得分:0)

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