The objectives for this post are to outline how to:
- Create a user account in AD
- Create a folder to hold the website code and assign the user read/execute rights
- Grant the user access to use ASP.NET
- Create an app pool running as our new identity
- Create an iis site assigned to the app pool and pointing at our folder
First off you will need to add a reference to Microsoft.web.Administration.dll, which is in
c:\windows\system32\InetSrv
These are the namespaces you’ll need:
using System; using System.Diagnostics; using System.DirectoryServices.AccountManagement; using System.IO; using System.Security.AccessControl; using Microsoft.Web.Administration;
To begin we need to get a handle on AD, specifically the container where we want our user to be created:
var usersContext = new PrincipalContext(ContextType.Domain, "MyDomain", "ou=Users,ou=MyDomain,dc=MyDomain");
Next we create the user:
var webUser = new UserPrincipal(usersContext, "username", "password", true); webUser.Save();
We then need to grant access to ASP.NET for the user (perhaps with v2 instead of v4)
Process.Start(@"c:\windows\microsoft.net\framework64\v4.0.30319\aspnet_regiis.exe", "-ga username");
Next we create the directory where we want the code to be housed, and grant the user read and execute permission on the folder:
var deploymentDir = Directory.CreateDirectory(fullPath);
var deploymentDirSecurity = deploymentDir.GetAccessControl();
deploymentDirSecurity.AddAccessRule(new FileSystemAccessRule("MyDomain\" + webUser.Name, FileSystemRights.ReadAndExecute, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
deploymentDir.SetAccessControl(deploymentDirSecurity);
Now we can create the app pool:
var manager = new ServerManager();
var applicationPool = manager.ApplicationPools.Add("My new app pool");
applicationPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
applicationPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
applicationPool.ProcessModel.UserName = parameters.Username;
applicationPool.ProcessModel.Password = parameters.Password;
And then the site:
var site = manager.Sites.Add("My new IIS site", "http", ":80:mydomain.com", fullPath);
site.Applications[0].ApplicationPoolName = "My new app pool";
manager.CommitChanges();
And there you have it