ahm*_*md0 8 .net c# asp.net security iis
在我的C#代码中,我需要为我的Web应用程序创建自定义标识并将其添加到IIS 7.我执行以下操作:
string strAppPoolName = "MyAppPool";
string strUserName = Environment.UserDomainName + "\\" + "myappusername";
addUserAccount(strUserName, strUserPass);
using (ServerManager serverManager = new ServerManager())
{
//Add application pool
ApplicationPool appPool = serverManager.ApplicationPools.Add(strAppPoolName);
appPool.AutoStart = true;
appPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
appPool.ManagedRuntimeVersion = "v4.0";
appPool.ProcessModel.MaxProcesses = 1;
//Assign identity to a custom user account
appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
appPool.ProcessModel.UserName = strUserName;
appPool.ProcessModel.Password = strUserPass;
}
Run Code Online (Sandbox Code Playgroud)
将用户添加到Active Directory的位置:
public static void addUserAccount(string sUserName, string sPassword)
{
using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain))
{
using (UserPrincipal up = new UserPrincipal(oPrincipalContext))
{
up.SamAccountName = sUserName;
up.SetPassword(sPassword);
up.Enabled = true;
up.PasswordNeverExpires = true;
up.Description = "My app's user account";
up.Save();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,当我稍后将该站点和应用程序添加到该应用程序池下的IIS 7时,Web应用程序无法运行,因为它没有足够的权限.更重要的是,对于我来说,某些.NET类(如System.Security.Cryptography)会因意外错误代码而失败,即使我手动将此新用户帐户的读/写权限设置为安装了我的Web应用程序的文件系统文件夹.
因此,在进行研究时,我发现了以下声明:
如果使用自定义标识,请确保您指定的用户帐户是Web服务器上IIS_IUSRS组的成员,以便该帐户具有对资源的适当访问权限.此外,在您的环境中使用Windows和Kerberos身份验证时,可能需要向域控制器(DC)注册服务主体名称(SPN).
那么,你是怎么做到的?
如果您需要将该帐户添加到 IIS_IUSERS 组(位于计算机本地),您可以使用该帐户GroupPrincipal
。请记住,PrincipalContext
为您的计算机创建一个本地域,而不是为用户使用的域域。您可以简单地按身份找到该组,然后将新创建的用户添加到集合中Members
。该Add
方法有一个接受UserPrincipal
.
你的代码会是这样的:
using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain))
{
using (PrincipalContext oGroupContext = new PrincipalContext(ContextType.Machine))
{
// find the local group IIS_IUSRS
using(var gp = GroupPrincipal.FindByIdentity(oGroupContext,"IIS_IUSRS"))
{
using (UserPrincipal up = new UserPrincipal(oPrincipalContext))
{
up.SamAccountName = sUserName;
up.SetPassword(sPassword);
up.Enabled = true;
up.PasswordNeverExpires = true;
up.Description = "My app's user account";
up.Save();
// add new user to Members of group
gp.Members.Add(up);
// save before Disposing!
gp.Save();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)