使用UserPrincipal更改AD用户帐户属性

时间:2012-04-24 14:51:30

标签: c# active-directory impersonation userprincipal

我正在尝试使用UserPrincipal更改Active Directory中的用户帐户属性。

我已经读过,我们必须使用对Active Directory具有写访问权限的特殊帐户,而不是当前登录用户。因此,我使用特殊帐户创建了一个特殊类来模仿。但我仍然有

System.UnauthorizedAccessException: General access denied error

at user.Save(ctx);线。

System.Security.Principal.WindowsImpersonationContext newUser = clsImpersonate.ImpersonateUser("ADUser", "ADPassword");

            if (newUser != null)
            {
                PrincipalContext ctx = blAD.GetAdminPrincipalContext();
                UserPrincipal user = blAD.GetUserPrincipal(this.SAMAccount);
                user.Enabled = false;
                user.Save(ctx);
                newUser.Undo();
            }

我如何达到这个要求?感谢。

3 个答案:

答案 0 :(得分:0)

您的特殊用户已授予了哪些权限?它需要能够对相关用户写userAccountControl

答案 1 :(得分:0)

我不会先冒充帐号!首先通过广告传递值来获得访问权限。

对于真正的问题,请查看错误:

  1. 获取principalContect。
  2. 获取userprincipal。
  3. 做你想做的事。
  4. 保存,你为什么要使用undo?删除撤消()。

答案 2 :(得分:0)

要以另一个用户身份访问Principle,请使用用户的凭据定义PrincipalContext,并在获取UserPrincipal时使用该PrincipalContext。

    PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain.tld", "ADUser", "ADPassword");
    UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, this.SAMAccount);
    if (user != null) 
    {
        user.Enabled = false;
        user.Save();
    }

如果您仍然收到UnauthorizedAccess异常,可能是因为您指定的帐户无权在Active Directory / LDS中的用户对象上写入userAccountControl属性。