Craig
Craig

Reputation: 889

IdentityServer4 - I need given_name claim in my API code, but don't have an identity token in my API. How can I get given_name?

I have a mobile client (Android), an API (WebAPI .net Core 3.1) and an IdentityServer4.

I login with my client to IdentityServer and get back an Identity token and a Access Token.

I use the access token to access the API... all good so far.

Now in the API, on the first time only, I need to update a table with the users first and last name plus some other identity stuff, but these claims are not available in the API (because this info is not available in the access token)

My question is, how do I go about getting the user claims from my API code?

I could pass the various claims as string parameters to the API call, but the mobile client is unable to see if this update has taken place, so I would have to pass this information every time I call the API, which is very wasteful as it is only required the first time. I also prefer this to be done without exposing this in an endpoint in my API.

Can anyone suggest how I can get the user (profile) claims of the user with in the API?

Update: Now I have found an endpoint in IdentityServer that could help, called "userinfo_endpoint" but this needs an Access Token. Can I somehow re-use the Access Token that is used to access the API within my API code?

Upvotes: 0

Views: 788

Answers (1)

Tore Nestenius
Tore Nestenius

Reputation: 19921

Yes, you can use the same access token to contact the user info endpoint to get additional user information.

If you were to use JavaScript to access it, it could look like:

        //Make a AJAX-call to the user endpoint
        $.ajax({
            url: "@OpenIDSettings.userinfo_endpoint",
            type: 'GET',
            headers: { "Authorization": 'Bearer ' + params.access_token }
        }).done(function (data) {

            $("#userinfo").text(JSON.stringify(data, null, 2));
        });

You just set the Authorization header.

You can also add user claims to the access token by providing UserClaims in your ApiScopes or ApiResource definitions, like:

new ApiScope()
{
    Name = "shop.admin",
    DisplayName = "You can administrate the e-shop systems",
    Description = "Full admin access to the e-shop system.",
    Emphasize = false,
    Enabled = true,
    Required = false,
    UserClaims = new List<string>
    {
        //Custom user claims that should be provided when requesting access to this API.
        //These claims will be added to the access token, not the ID-token!
        "seniority",
    }
}

Upvotes: 1

Related Questions