首页 > 解决方案 > IdentityServer4 - 我的 API 代码中需要 given_name 声明,但我的 API 中没有身份令牌。我怎样才能得到given_name?

问题描述

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

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

我使用访问令牌来访问 API ......到目前为止一切都很好。

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

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

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

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

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

标签: identityserver4access-tokenclaims-based-identity

解决方案


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

如果您要使用 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));
        });

您只需设置 Authorization 标头。

您还可以通过在 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",
    }
}

推荐阅读