租户和用户身份的多个ClaimsIdentity实例

时间:2014-11-04 12:29:10

标签: asp.net .net authentication claims-based-identity claims

假设我有一个多租户.NET应用程序,每个租户都拥有自己的用户。当请求进入我的Web服务器时,我需要先确定租户。稍后,我将尝试根据通过HTTP标头传递的信息对用户进行身份验证。此时,我实际上有两个身份:一个用于租户,另一个用于用户。以下代码解释了我想要做的意图:

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 });
    }
}

我在这里做的是基于两个ClaimsPrincipal实例创建一个ClaimsIdentity实例。对于多租户应用程序,这是在.NET服务器应用程序中处理租户和用户身份的正确方法吗?

1 个答案:

答案 0 :(得分:0)

我会坚持使用单一身份和其他声明,以便您识别租户。这就是我们一直这样做的方式。

通过这种方式,您可以验证用户是否尝试切换到其他租户并重新进行身份验证(发布新的声明集)或禁止访问。