通过 IdentityServer 身份验证后如何获取 WebAPI 控制器上的用户信息? [英] How to get user's information on WebAPI controller after authenticated with IdentityServer?

查看:32
本文介绍了通过 IdentityServer 身份验证后如何获取 WebAPI 控制器上的用户信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot get user's information on WebAPI controller after my client app authenticates with IdentityServer3 successfully. Below are the steps:

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

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

Could anyone provide me some helps how to get user's data on WebAPI?

推荐答案

如果你使用owin,可以试试这段代码.

if you use owin, you can try this code.

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

这篇关于通过 IdentityServer 身份验证后如何获取 WebAPI 控制器上的用户信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆