How do I get user information on a WebAPI controller after authenticating with IdentityServer?

I cannot get user information on the WebAPI controller after successfully authenticating my client application with IdentityServer3. Below are the steps:

  • "Login with profile and access token" successfully with Implicit Client JavaScript Application
  • I can see the user's data in the "Identity ID Content" pane enter image description here
  • I am doing a Call service in my WebAPI service, I see a lot of claims in the ClaimsPrincipal but cannot get values ​​like email, roles mapped to client side. Below is the code and answers.

enter image description here Can anyone provide me with some help on how to get user data on WebAPI?

+3


source to share


1 answer


If you are using 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));
    }

      

+5


source







All Articles