2013-10-05 60 views
8

在我的C#代码,我需要为我的web应用程序创建一个自定义的身份,并将其添加到IIS 7,我做了以下内容:编程设置用户帐户进行自定义的身份应用程序池在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; 
} 

当用户添加到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(); 
     } 
    } 
} 

的问题是,当我的网站和应用程序后添加到IIS 7下的应用程序池,Web应用程序无法运行,因为它没有足够的权限。更重要的是,对于我来说,即使我手动将这个新用户帐户的读/写权限设置为安装了我的Web应用程序的文件系统文件夹,某些.NET类(如System.Security.Cryptography)也会失败,并显示意外的错误代码。

所以,在做一个研究,我发现了following statement

如果使用自定义标识,请确保您 指定用户帐户是IIS_IUSRS组的Web服务器上的一个成员,这样 该帐户有适当的资源访问权限。此外,当您在您的环境中使用Windows和Kerberos身份验证时,您可能需要向域 控制器(DC)注册服务主体名称(SPN)。

那么,你是如何做到这一点的?

+0

看它是否可以帮助你。 http://stackoverflow.com/questions/20138781/how-to-give-folder-permission-for-iis-user-in-c – gpaoli

+0

就像它是解释你必须添加你的新用户到IIS_IUSRS组是一个AD集团 – D4rkTiger

回答

0

如果您需要将该帐户添加到IIS_IUSERS组(本机在本机上),则可以使用​​。请记住,要为您的计算机创建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(); 
      } 
     } 
    } 
} 
相关问题