How to get user's information on WebAPI controller after authenticated with IdentityServer?

依然范特西╮ 提交于 2019-12-05 03:08:46

问题


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

  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.

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

回答1:


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


来源:https://stackoverflow.com/questions/31160965/how-to-get-users-information-on-webapi-controller-after-authenticated-with-iden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!