hazjack
hazjack

Reputation: 1715

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

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 enter image description here
  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.

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

Upvotes: 4

Views: 9025

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

Upvotes: 5

Related Questions