调用的目标抛出了异常。在UserPrincipal抛出

时间:2014-07-22 14:24:33

标签: asp.net-mvc active-directory adfs

我正在尝试在AD上创建一个新用户。我正在使用以下代码:

        using (var context = new PrincipalContext(ContextType.Domain, this.DomainName, userWithWMIAccessRights, userWithWMIAccessrightsPassword))
        {
            UserPrincipal user = new UserPrincipal(context);
            user.DisplayName = Newusername;
            user.Name = Newusername;
            user.Enabled = true;
            user.SetPassword(passwordOfThenewUser);
            user.Save(); //<-- throws exception InnerException = {"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}
            return user;
        }

我设置了userWithWMIAccessrightsPassword:

  • userWithWMIAccessrightsPassword是Enterpirse管理员,域管理员和域用户的成员
  • 从命令提示符处运行dcomcnfg。
  • 从服务列表中选择Windows Management Instrumentation。
  • 通过从“安全”标签添加userWithWMIAccessrightsPassword帐户更新了自定义权限,并授予他完全权限。

Web应用程序托管在与AD运行相同的计算机上。当我使用Visual Studio调试Web应用程序时,用户和密码设置没有问题。

当在AD机器上部署web应用程序时,创建用户的函数会在设置密码的代码行中抛出{“访问被拒绝。(HRESULT异常:0x80070005(E_ACCESSDENIED))”}。用户已创建,未启用且没有密码。

当PrincipalContext使用具有完全权限的AD用户时,为什么我会拒绝访问?

1 个答案:

答案 0 :(得分:0)

好的,似乎PrincipalContext是!= impersionating。

我可以用以下方法解决问题:

1。)设置PrincipalContext的容器并调用ValidateCredentials(this.UserName,this.Password,ContextOptions.Negotiate)。

2)。

using (new Impersonator(this.UserName, this.DomainName, this.Password, LogonType.LOGON32_LOGON_SERVICE, LogonProvider.LOGON32_PROVIDER_WINNT40))
        {
            using (var context = CreatePrincipalContext())
            {
                UserPrincipal user = new UserPrincipal(context);
                user.DisplayName = username;
                user.Name = username;
                user.Enabled = true;
                user.SetPassword(password);
                user.Save();
                return user;
            }
        }

但我仍然对使用Principalcontext的模拟类的需要感到困惑。我认为PrincipalContext取代了impersionate类。