使用 ASP.NET C# 在 AD 中创建用户时无法使用 DirectoryEntry.Invoke 设置密码

Cannot set password with DirectoryEntry.Invoke when user is created in AD using ASP.NET C#

Web 应用程序正在从人事管理页面创建用户,然后将用户添加到 Active Directory。这是执行此操作的代码:

DirectoryEntry Folder = new DirectoryEntry("LDAP://XXXX.com/CN=ContainerName, DC=XXXX, DC=com", admin, adminPwd, AuthenticationTypes.None);

    if (Folder.SchemaEntry.Name == "container")
    {
        DirectoryEntry user = Folder.Children.Add("CN=" + txtFirstname.Text + " " + txtLastname.Text, "User");

        if (DirectoryEntry.Exists(user.Path))
        {
            // Error Msg Here
        }
        else
        {
            // Required attributes
            if (txtFirstname.Text != "" && txtLastname.Text != "") { user.Properties["sAMAccountName"].Value = txtFirstname.Text.ToLower() + "." + txtLastname.Text.ToLower(); }
            if (txtFirstname.Text + " " + txtLastname.Text != "") { user.Properties["cn"].Value = txtFirstname.Text + " " + txtLastname.Text; }
            // More controls to populate Optional AD attributes.  Not entered to conserve space.  The code works however.

            user.CommitChanges();

            int val = (int)user.Properties["userAccountControl"].Value;
            user.Properties["userAccountControl"].Value = val & ~0x2;
            user.Properties["pwdLastSet"].Value = 0;
            user.CommitChanges();
            user.Invoke("SetPassword", new object[] { "SuperSecretPassword" });
            user.CommitChanges();
        }

问题是创建账号后,invoke方法设置密码失败。每次尝试设置密码 returns 在 catch 语句中出现此错误:

System.Reflection.TargetInvocationException was caught
HResult=-2146232828
Message=Exception has been thrown by the target of an invocation.
Source=System.DirectoryServices
StackTrace:
   at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)
   at Personnel_Govt.CreateUser() in c:\inetpub\wwwroot\TestingFolder\Personnel\Add\Govt.aspx.cs:line 148
   at Personnel_Govt.btnSubmit_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\TestingFolder\Personnel\Add\Govt.aspx.cs:line 95
InnerException: System.UnauthorizedAccessException
   HResult=-2147024891
   Message=One or more input parameters are invalid

   Source=Active Directory
   InnerException: 

如果在AD中手动设置密码,并在创建帐户后勾选'Reset Required',就可以了。

为什么设置密码的方法失败了???

问题已解决。显然,Internet 信息服务帐户 (IIS_IUSRS) 没有为 Active Directory 设置密码的权限。它可以更改密码但不能设置密码。

要允许 ASP.NET 页面在创建帐户时设置 AD 密码,我必须 运行 "Active Directory Users and Computers",右键单击域,select "Delegate Control"。这将打开一个向导,允许您授予帐户 IIS_IUSRS 更改 AD 的权限。