如何在使用IdentityServer进行身份验证后获取WebAPI控制器上的用户信息?

haz*_*ack 4 c# jwt asp.net-web-api owin identityserver3

在我的客户端应用程序成功验证IdentityServer3后,我无法在WebAPI控制器上获取用户信息.以下是步骤:

  1. JavaScript Implicit Client应用程序成功登录"使用配置文件和访问令牌"
  2. 我在"ID令牌内容"面板上看到用户的数据 在此输入图像描述
  3. 我对我的WebAPI服务进行"呼叫服务",我在ClaimsPrincipal中看到了许多声明,但无法获取客户端显示的电子邮件,角色等值.以下是代码和回复.

在此输入图像描述 任何人都可以帮我提供一些如何在WebAPI上获取用户数据的帮助吗?

小智 5

如果您使用owin,您可以尝试此代码.

 var owinUser = TryGetOwinUser();
 var claim= TryGetClaim(owinUser, "email");
 string email = claim.Value;

 private ClaimsPrincipal TryGetOwinUser()
    {
        if (HttpContext.Current == null)
            return null;

        var context = HttpContext.Current.GetOwinContext();
        if (context == null)
            return null;

        if (context.Authentication == null || context.Authentication.User == null)
            return null;

        return context.Authentication.User;
    }

    private Claim TryGetClaim(ClaimsPrincipal owinUser, string key)
    {
        if (owinUser == null)
            return null;

        if (owinUser.Claims == null)
            return null;

        return owinUser.Claims.FirstOrDefault(o => o.Type.Equals(key));
    }
Run Code Online (Sandbox Code Playgroud)