ASP.NET MVC 5 获得声明

ASP.NET MVC 5 get claims

我使用第三方 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;

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

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

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