ASP.NET MVC 5获得了声明

时间:2017-03-19 13:47:04

标签: c# asp.net-mvc claims-based-identity claims asp.net-identity-3

我使用第三方auth nuget instagram软件包进行登录并设置新的声明:

        app.UseInstagramAuthentication(new InstagramAuthenticationOptions
        {
            ClientId = "XXXXXXXXXXXXXXXXXXXXXXXXX",
            ClientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXX",
            Provider = new InstagramAuthenticationProvider()
            {
                OnAuthenticated = (context) =>
                {
                    context.Identity.AddClaim(new Claim("urn::instagram::accesstoken", context.AccessToken));
                    return Task.FromResult(0);
                }
            }

但当我试图获得此声明时

        var ctx = HttpContext.GetOwinContext();
        ClaimsPrincipal user = ctx.Authentication.User;
        IEnumerable<Claim> claims = user.Claims;

此声明在列表中不存在。为什么呢?

1 个答案:

答案 0 :(得分:3)

您需要在外部登录时检索并存储这些声明,可能类似于:

private async Task StoreAuthTokenClaims(ApplicationUser user)
{
    // 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);
            }
        }
    }
}

并使用ExternalLoginConfirmation方法:

result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
    await StoreAuthTokenClaims(user);

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

之后,您可以检索如下声明:

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