在 C# 中使用密码创建 Active Directory 用户
- 作者: 贫道化缘不化斋
- 来源: 51数据库
- 2022-10-21
问题描述
我正在寻找一种方法来创建 Active Directory 用户并设置他们的密码,最好不授予我的应用程序/服务域管理员权限.
I'm looking for a way to create Active Directory users and set their password, preferably without giving my application/service Domain ***** 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 ***** privileges. As I don't really see the point to grant my code Domain ***** 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
