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

查看:698
本文介绍了经过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令牌内容"面板上看到用户的数据
  3. 我对WebAPI服务进行了呼叫服务",我在ClaimsPrincipal中看到许多声明,但是无法获取诸如电子邮件,在客户端显示的角色之类的值.以下是代码和回应.
  1. "Login With Profile and Access Token" successfully from JavaScript Implicit Client app
  2. I see user's data on "ID Token Contents" panel
  3. I do "Call service" to my WebAPI service, I see many claims in ClaimsPrincipal but cannot get values such as email, roles displayed on client side. Below are code & responses.

谁能为我提供一些帮助,以获取如何在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天全站免登陆