IdentityServer4 - 我需要 given_name 在我的 API 代码中声明,但在我的 API 中没有身份令牌。我怎样才能得到given_name?

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?

我有一个移动客户端 (Android)、一个 API (WebAPI .net Core 3.1) 和一个 IdentityServer4。

我用我的客户端登录到 IdentityServer 并取回身份令牌和访问令牌。

我使用访问令牌访问 API...到目前为止一切正常。

现在在 API 中,仅在第一次,我需要用用户的名字和姓氏以及一些其他身份信息更新 table,但这些声明在API(因为此信息在访问令牌中不可用)

我的问题是,如何从我的 API 代码中获取用户声明?

我可以将各种声明作为字符串参数传递给 API 调用,但移动客户端无法查看此更新是否已发生,因此我每次调用时都必须传递此信息API,这是非常浪费的,因为它只在第一次需要。我也更喜欢这样做而不在我的 API.

的端点中暴露它

谁能建议我如何在 API 中获取用户的用户(个人资料)声明?

更新: 现在我在 IdentityServer 中找到了一个可以提供帮助的端点,称为“userinfo_endpoint”,但这需要一个访问令牌。我能否以某种方式在我的 API 代码中重新使用用于访问 API 的访问令牌?

是的,您可以使用相同的访问令牌联系用户信息端点以获取其他用户信息。

如果您使用 JavaScript 访问它,它可能看起来像:

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

您刚刚设置了授权header。

您还可以通过在 ApiScopes 或 ApiResource 定义中提供 UserClaims,将用户声明添加到访问令牌,例如:

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",
    }
}