使用C#中的密码创建Active Directory用户

时间:2010-02-21 12:35:00

标签: c# .net active-directory

我正在寻找一种创建Active Directory用户并设置密码的方法,最好不要提供我的应用程序/服务域管理员权限。

我尝试了以下内容:

DirectoryEntry newUser = _directoryEntry.Children.Add("CN=" + fullname, USER);
newUser.Properties["samAccountName"].Value = username;
newUser.Properties["userPassword"].Value = password;
newUser.Properties["mail"].Value = email;
newUser.CommitChanges();

用户已创建,但似乎从未在用户上设置密码。

有没有人知道在创建用户时如何设置用户密码?我知道

.Invoke("SetPassword", new object[] { password })

但这需要我的代码以域管理员权限运行。因为我没有真正看到授予我的代码域管理员权限的重点,只是设置初始密码(我也允许用户密码重置,但那些在特定用户的上下文中运行),我希望有人聪明解决方案不要求我这样做。

提前致谢!

4 个答案:

答案 0 :(得分:33)

现在使用System.DirectoryServices.AccountManagement可以更轻松地完成整个过程(只要您使用.Net 3.5):

See here for a full rundown

以下是您具体案例的简要示例:

using(var pc = new PrincipalContext(ContextType.Domain))
{
  using(var up = new UserPrincipal(pc))
  {
    up.SamAccountName = username;
    up.EmailAddress = email;
    up.SetPassword(password);
    up.Enabled = true;
    up.ExpirePasswordNow();
    up.Save();
  }
}

答案 1 :(得分:4)

我使用@ Nick的代码(包含在using语句中,以便正确处理上下文和主体)。至于权限,您至少需要在创建用户的OU上拥有足够的权限来创建和管理对象。我将创建一个特定的用户来运行您的程序,并为其提供足够的权限来执行特定OU中所需的任务,而不再需要。

答案 2 :(得分:4)

是也可以使用以下代码创建大量用户

DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");

for (int i = 0; i < 10; i++)
{
    try
    {
        DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i,  "user");
        childEntry.CommitChanges();
        ouEntry.CommitChanges();
        childEntry.Invoke("SetPassword", new object[] { "password" });
        childEntry.CommitChanges();
    }
    catch (Exception ex)
    {
    }
}

答案 3 :(得分:0)

尝试使用此代码。

DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local");

for (int i = 0; i < 10; i++)
{
    try
    {
        DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i,  "user");
        childEntry.CommitChanges();
        ouEntry.CommitChanges();
        childEntry.Invoke("SetPassword", new object[] { "password" });
        childEntry.CommitChanges();
    }
    catch (Exception ex)
    {

    }
}
相关问题