【问题标题】:How to get user's information on WebAPI controller after authenticated with IdentityServer?通过 IdentityServer 认证后如何获取 WebAPI 控制器上的用户信息?
【发布时间】:2015-09-18 14:08:49
【问题描述】:

在我的客户端应用程序成功通过 IdentityServer3 进行身份验证后,我无法在 WebAPI 控制器上获取用户信息。步骤如下:

  1. JavaScript Implicit Client app 成功“使用配置文件和访问令牌登录”
  2. 我在“ID Token Contents”面板上看到了用户数据
  3. 我对我的 WebAPI 服务执行“呼叫服务”,我在 ClaimsPrincipal 中看到许多声明,但无法获取电子邮件、客户端显示的角色等值。以下是代码和响应。

谁能帮助我如何在 WebAPI 上获取用户数据?

【问题讨论】:

  • 你有没有想过这个问题?我正在努力解决同样的问题。

标签: c# asp.net-web-api owin jwt identityserver3


【解决方案1】:

如果你使用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));
    }

【讨论】:

  • 感谢您的回答,@Serdar。我可以像您的代码一样获得 owincontext,但声明是相同的。有 Type=scope 和 Value = email 的声明,没有你所说的 Type = email 的声明。你有其他想法吗?
  • 索赔不通过电子邮件发送信息。您可以在登录时将声明(“电子邮件”)添加到声明中
  • 登录是由 IdentityServer 完成的,我不知道我的 WebAPI 服务中的电子邮件是什么。您在示例客户端应用程序中看到,它可以从令牌中解析所有信息,包括电子邮件地址和角色i.stack.imgur.com/mwSCi.png
  • 是的,它在 github github.com/IdentityServer/IdentityServer3/tree/master/source/… 但我还没有看 :)
  • 您可以在身份应用程序上找到登录功能。您可以编辑声明。github.com/IdentityServer/IdentityServer3/blob/master/source/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 2021-09-08
  • 2013-08-02
  • 2020-01-19
  • 2021-08-03
  • 2022-01-10
相关资源
最近更新 更多