简体   繁体   中英

How do I create an AD group using GroupPrincipal in C# .NET 4.5?

I'm trying to create an AD group in a C# .NET web app. The app is running in an app pool with user rights to create groups. If I attempt to create a group after logging in as that user, it works fine, but not from the web app. This is the relevant code:

Log.debug("Testing group creation (apptest).");
PrincipalContext gpc = new PrincipalContext(ContextType.Domain, "FOO", "OU=Groups,OU=Foo,OU=Bar,OU=Baz,DC=corp,DC=edu");
GroupPrincipal gp = new GroupPrincipal(gpc, "apptest");
gp.Description = "test";
gp.IsSecurityGroup = true;
gp.GroupScope = GroupScope.Global;
gp.Save();
Log.debug("Group created successfully.");

Using the user/apppool this is running as, I can look up groups and users fine. I can enumerate the "Groups" OU and see other groups in there.

If I try with the above OU string, I get "Access is denied" when calling gp.Save(), which makes me wonder if it's a problem because it's running as a webapp or something related to that, because it works manually. Or maybe I haven't set up the GroupPrincipal object correctly.

If I try with CN=apptest prepended to the OU string, I get "There is no such object on the server" when creating the GroupPrincipal, which makes me think that the original string above is probably correct.

Is this code correct, in theory?

Almost all examples I've found use the LDAP and Directory stuff, which I don't want to use, and am not supposed to use (the team wants to use the newer stuff). The other examples weren't creating groups.

Update: Trying Save(gpc) doesn't work either, and there are no groups existing already with that name.

This is a very old post, but I was searching for the answer myself, and what worked for me is to do exactly as specified in the post, except for the way principal context is created. This is how I am creating principal context:

new PrincipalContext(ContextType.Domain, serverName, userWithAccess, userWithAccessPassword);

I did not check if it works in 4.5 as I did not need this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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