在 UserPrincipal 上调用 Save 函数时将用户添加到 Active Directory Exception

Add user to Active Directory Exception while calling Save function on UserPrincipal

我正在制作一个用于将新用户添加到 Active Directory 的小型表单应用程序。

创建 PrincipalContext 后,我​​正在创建 UserPrincipal 并设置它的属性。

当我在 UserPrincipal 上调用 Save 时,抛出以下异常:

System.DirectoryServices.AccountManagement.PrincipalOperationException: The validation information class requested was invalid. (Exception from HRESULT: 0x80070544) ---> System.Runtime.InteropServices.COMException: The validation information class requested was invalid.

下面代码的相关部分:

PrincipalContext principalContext = null;

try
{
    principalContext = new PrincipalContext(ContextType.Domain, 
        "abc.com", "OU=ouname,DC=abc,DC=com", ContextOptions.Negotiate, uName, pWord);
}
catch (Exception e)
{
    return "Failed to create PrincipalContext. Exception: " + e;
}

// Check if user object already exists in the store
UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, userLogonName);

if (usr != null)
{
    return userLogonName + " already exists. Please use a different User Logon Name.";
}

// Create the new UserPrincipal object
UserPrincipal userPrincipal = new UserPrincipal(principalContext);


if (lastName != null && lastName.Length > 0)
{ 
    userPrincipal.Surname = lastName;
}

if (firstName != null && firstName.Length > 0)
{
    userPrincipal.GivenName = firstName;
}

if (userLogonName != null && userLogonName.Length > 0)
{
    userPrincipal.EmailAddress = userLogonName + "@abc.com";
}

if (userLogonName != null && userLogonName.Length > 0)
{
    userPrincipal.SamAccountName = userLogonName;
    userPrincipal.UserPrincipalName = userLogonName;
}

string pwdOfNewlyCreatedUser = "abc123$$$!ABC";
userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

userPrincipal.Enabled = true;
userPrincipal.ExpirePasswordNow();

try
{
    userPrincipal.Save();
}
catch (Exception e)
{
    return "Exception creating user object. " + e;
}

为清楚起见编辑: 这一行是捕获异常的地方:“userPrincipal.Save();”

以上代码取自这里:

https://docs.microsoft.com/en-us/previous-versions/bb384369(v=vs.90)

我不知道从这里到哪里去。

编辑:进一步调查指向密码的设置。如果我删除以下行,则会创建用户:

string pwdOfNewlyCreatedUser = "abc123$$$!ABC";
userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

但我不想删除这些行。或者更具体地说,我不想不设置密码。

解决了这个问题。或者更确切地说,已经解决了它。

在尝试以多种不同方式设置密码后,我确定了一种简单有效的方式。

而不是

string pwdOfNewlyCreatedUser = "abc123$$$!ABC";
userPrincipal.SetPassword(pwdOfNewlyCreatedUser);

userPrincipal.Enabled = true;
userPrincipal.ExpirePasswordNow();

try
{
    userPrincipal.Save();
}
catch (Exception e)
{
    return "Exception creating user object. " + e;
}

我这样做:

userPrincipal.Enabled = true;

try
{
    userPrincipal.Save();

    userPrincipal.ChangePassword("", "abc123$$$!ABC");
    userPrincipal.ExpirePasswordNow();
    userPrincipal.Save();

}
catch (Exception e)
{
    return "Exception creating user object. " + e;
}

总结:SetPassword 不工作,但在使用 ChangePassword 保存用户后工作。