2013-10-05 56 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(); 
      } 
     } 
    } 
} 
相關問題