对LOCAL AUTHORITY声明和外部提供商声明的混淆

时间:2015-02-26 16:44:44

标签: asp.net facebook asp.net-web-api oauth-2.0 claims-based-identity

我正在创建一个简单的WebApi,允许用户与Facebook连接。当我从facebook获取accessToken时,我正在调用RegisterExternal来创建Asp.Net Identity记录并存储来自令牌的声明。这些声明还包括我稍后查询facebook图表所需的访问令牌。到目前为止,一切似乎都很好。

我遇到的问题是阅读索赔。我可以看到他们在我的数据库中我只是想弄清楚如何查询这些数据。我试过了

var claimsIdentity = User.Identity as ClaimsIdentity;

但是这给了我2个索赔 a)" http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" b)角色

这两个都是发行人LOCAL AUTHORITY(说实话我不确定它们何时被创建,因为我没有明确添加这些)。因此,我认为他们要么将我对数据库的声明再次保存为错误类型的发行者,要么是混淆了

await userManager.AddClaimAsync(user.Id, new Claim("urn:facebook:access_token", accessTokenClaim.Value, ClaimValueTypes.String, "LOCAL AUTHORITY"));

或我访问声明的代码不正确。

有人可以对此有所了解吗?

3 个答案:

答案 0 :(得分:0)

在向您的身份添加声明时:

// Get the claims identity
    ClaimsIdentity claimsIdentity =
        await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

    if (claimsIdentity != null)
    {
        // Retrieve the existing claims
        var currentClaims = await UserManager.GetClaimsAsync(user.Id);

        // Get the list of access token related claims from the identity
        var tokenClaims = claimsIdentity.Claims
            .Where(c => c.Type.StartsWith("urn:tokens:"));

        // Save the access token related claims
        foreach (var tokenClaim in tokenClaims)
        {
            if (!currentClaims.Contains(tokenClaim))
            {
                await UserManager.AddClaimAsync(user.Id, tokenClaim);
            }
        }
    }

要将这些声明持久保存到数据库,您必须为用户调用SignIn:

// Sign in and redirect the user
    await SignInAsync(user, isPersistent: false);

要稍后检索声明,您只需使用:

var claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
if (claimsIdentity != null)
   var claims = claimsIdentity.Claims;

此代码由本文的摘录组成:http://www.jerriepelser.com/blog/get-the-twitter-profile-image-using-the-asp-net-identity

如果你想看一个完整的例子,我建议你仔细阅读。我自己使用了本文中的代码,它在我的项目中对Twitter和Facebook外部声明都很有用。

答案 1 :(得分:0)

我在重命名身份Cookie时遇到了同样的问题。所以我在2个cookie中有2个不同的用户。删除旧版后,问题就消失了。

答案 2 :(得分:0)

如果创建索赔时未指定

LOCAL_AUTHORITY,则它是Issuer的默认值。例如: var Claim = new Claim(“ LastName”,“ Timberlake”,“ string”,“ http:/contoso.com/someissuername”); 上例中的最后一个参数是颁发者。