创建用户 Active Directory:调用目标抛出异常。抛给 UserPrincipal

Create user Active Directory: Exception has been thrown by the target of an invocation. thrown at UserPrincipal

当我尝试在活动目录中创建用户时出现异常:

(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) error

代码:

UserPrincipal userPrincipal = new UserPrincipal(principalContext);
userPrincipal.SamAccountName = serviceAccount.SAMAccountName;
userPrincipal.PasswordNeverExpires = serviceAccount.PasswordNeverExpires;
userPrincipal.SetPassword(passwordOfAccount);
userPrincipal.Enabled = serviceAccount.Enabled;

// Creates the account
try
{
    userPrincipal.Save();
}
catch (Exception e)
{
    return false;
}
return true;

我在

收到错误
userPrincipal.Save();

E_ACCESSDENIED 表示您用于执行此操作的帐户没有执行您正在执行的操作的权限。

您没有在创建 PrincipalContext 对象的地方显示您的代码,但如果您没有给它用户名和密码,那么它会使用进程 运行 下的任何凭据, 听起来还不够好。

您需要使用 one of the PrincipalContext constructors that lets you provide a username and password。例如:

var principalContext = new PrincipalContext(
                            ContextType.Domain,
                            "example.com",
                            "ou=Users,dc=example,dc=com",
                            "username",
                            "password"
                       );

其中 "example.com" 是您的域名,""ou=Users,dc=example,dc=com"" 是您要创建帐户的 OU,"username""password" 属于具有在该 OU 中创建用户帐户的权限。