2014-11-04 51 views
0

假設我有一個多租戶.NET應用程序,其中每個租戶都擁有自己的用戶。當請求到達我的Web服務器時,我需要先確定租戶。稍後,我將嘗試根據通過HTTP標頭傳遞的信息對用戶進行身份驗證。此時,我確實有兩個身份:一個用於租戶,另一個用於用戶。下面的代碼說明了什麼,我想要做的意圖:租戶和用戶身份的多個ClaimsIdentity實例

class Program 
{ 
    static void Main(string[] args) 
    { 
     // NOTE: The below is a sample of how we may construct a ClaimsPrincipal instance over two ClaimsIdentity instances: 
     //  one for the tenant identity and the the other for the user idenetity. When a request come to the web server, we can determine the 
     //  tenant's identity at the very early stages of the request lifecycle. Then, we can try to authenticate the user based on the 
     //  information passed through the request headers (this could be bearer token, basic auth, etc.). 

     const string authServerName = "urn:myauthserver"; 
     const string tenantAuthType = "Application"; 
     const string userAuthType = "External"; 

     const string tenantId = "f35fe69d-7aef-4f1a-b645-0de4176cd441"; 
     const string tenantName = "bigcompany"; 
     IEnumerable<Claim> tenantClaims = new Claim[] 
     { 
      new Claim(ClaimTypes.NameIdentifier, tenantId, ClaimValueTypes.String, authServerName), 
      new Claim(ClaimTypes.Name, tenantName, ClaimValueTypes.String, authServerName) 
     }; 

     const string userId = "d4903f71-ca06-4671-a3df-14f7e02a0008"; 
     const string userName = "tugberk"; 
     const string twitterToken = "30807826f0d74ed29d69368ea5faee2638b0e931566b4e4092c1aca9b4db04fe"; 
     const string facebookToken = "35037356a183470691504cd163ce2f835419978ed81c4b7781ae3bbefdea176a"; 
     IEnumerable<Claim> userClaims = new Claim[] 
     { 
      new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, authServerName), 
      new Claim(ClaimTypes.Name, userName, ClaimValueTypes.String, authServerName), 
      new Claim("token", twitterToken, ClaimValueTypes.String, authServerName, "Twitter"), 
      new Claim("token", facebookToken, ClaimValueTypes.String, authServerName, "Facebook") 
     }; 

     ClaimsIdentity tenantIdentity = new ClaimsIdentity(tenantClaims, tenantAuthType, ClaimTypes.Name, ClaimTypes.Role); 
     ClaimsIdentity userIdentity = new ClaimsIdentity(userClaims, userAuthType, ClaimTypes.Name, ClaimTypes.Role); 

     ClaimsPrincipal principal = new ClaimsPrincipal(new[] { tenantIdentity, userIdentity }); 
    } 
} 

我在做什麼這裏是基於兩個ClaimsIdentity實例創建ClaimsPrincipal實例。對於多租戶應用程序,這是在.NET服務器應用程序中處理租戶和用戶身份的正確方法嗎?

回答

0

我會堅持一個單一的身份與額外的索賠,讓您識別租戶。這是我們總是這樣做的。

通過這種方式,您可以驗證用戶是否嘗試切換到另一個租戶並重新進行身份驗證(發出新的聲明集)或禁止訪問。

+0

Thx。 '這樣你可以驗證用戶是否試圖切換到另一個租戶':這不是一個案例。每個租戶在其單獨的數據存儲系統內都有自己的用戶身份管理。 – tugberk 2014-11-04 13:14:40