【问题标题】:Change Password Windows AD C#更改密码 Windows AD C#
【发布时间】:2015-09-09 17:24:12
【问题描述】:

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

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

【问题讨论】:

    标签: c# windows active-directory passwords impersonation


    【解决方案1】:

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

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

    【讨论】:

    • 我仍然收到“拒绝访问”
    • 那么您指定的用户没有更改用户密码的权限或新密码不符合 Active Directory 中定义的要求。
    • 使用SetPassword时用户是否有权更改密码并不重要,除非他们也是AD中的管理员;要么使用带有SetPassword 的管理员 AD 帐户,要么查看我的答案以了解更改用户 AD 密码的替代方法。
    【解决方案2】:

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

    up.SetPassword(txtNewChangedPassword.Text);
    

    有了这个:

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

    【讨论】:

      【解决方案3】:
                  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);
                  }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-16
        • 2018-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多