【问题标题】:ASP.NET MVC 5 get claimsASP.NET MVC 5 获得声明
【发布时间】:2017-03-19 13:47:03
【问题描述】:

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

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

【问题讨论】:

  • 显然,因为 user.Claims 进入数据库,它不会读取该信息的不记名令牌。

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 2016-01-28
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多