简体   繁体   English

如何在C#中创建属于Domain Admins组的AD用户

[英]How to create AD User belonging to Domain Admins group in C#

I'm working on a C# project which auto-creates new Active Directory users and let them access to the AD server. 我正在研究一个C#项目,该项目会自动创建新的Active Directory用户并允许他们访问AD服务器。

I have made a general user with the following code, but since the user does not belong to Domain Admins, it could not access to the server. 我使用以下代码使普通用户成为可能,但是由于该用户不属于Domain Admins,因此它无法访问服务器。

Domain domain = Domain.GetCurrentDomain();
PrincipalContext context = new PrincipalContext(ContextType.Domain);

UserPrincipal principal = new UserPrincipal(context);
principal.Name = name;
principal.UserPrincipalName = name + "@" + domain.Name;
principal.SamAccountName = name;
principal.Enabled = true;
principal.SetPassword(password);
principal.PasswordNeverExpires = true;
principal.Save();

Is there a way to include which group the new user belong in the code? 有没有办法在代码中包括新用户所属的组? Or after creating the account, adding the user to Domain Admins group might be another solution but I couldn't figure out how to do this either. 或者在创建帐户后,将用户添加到Domain Admins组可能是另一种解决方案,但是我也无法弄清楚该怎么做。 Any advice would be appreciated. 任何意见,将不胜感激。

You just need to find the group and add the user you created. 您只需要找到组并添加您创建的用户。 Like this: 像这样:

var group = GroupPrincipal.FindByIdentity(context, "Domain Admins");
group.Members.Add(principal);
group.Save();

The code will have to run with credentials that can add someone to the Domain Admins group, which is likely a domain admin account itself. 该代码必须使用可以将某人添加到Domain Admins组的凭据运行,这很可能是域管理员帐户本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM