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

11

本文介绍了在 C# 中使用密码创建 Active Directory 用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在寻找一种方法来创建 Active Directory 用户并设置他们的密码,最好不授予我的应用程序/服务域管理员权限.

I'm looking for a way to create Active Directory users and set their password, preferably without giving my application/service Domain Admin privileges.

我尝试了以下方法:

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();

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

The user is created, but it seems the password is never set on the user.

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

Does anyone have an idea on how to set the user's password initially when creating the user? I know about

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

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

But that requires my code to be run with Domain Admin privileges. As I don't really see the point to grant my code Domain Admin privileges, just to set the initial password (I also allow user password resets, but those run in the context of that particular user), I am hoping someone has a clever solution that doesn't require me to do so.

提前致谢!

推荐答案

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

You can do this whole process much easier now with System.DirectoryServices.AccountManagement (long as you're on .Net 3.5):

请参阅此处了解完整概要

以下是您的具体案例的快速示例:

Here's a quick example of your specific case:

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();
  }
}

这篇关于在 C# 中使用密码创建 Active Directory 用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14