【问题标题】:unable to use validate jwt in APIM for managed Identity token无法在 APIM 中对托管身份令牌使用验证 jwt
【发布时间】:2021-12-26 14:30:03
【问题描述】:

我们在 APIM 中有一个验证 jwt 策略来验证 jwt 令牌。我们正在使用 azure.identity 库从我们的函数应用生成令牌。到目前为止,我们使用系统分配的身份使用以下方法生成令牌。

var tokenCredential = new DefaultAzureCredential();
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { "https://management.azure.com" + "/.default" }) { });

令牌生成成功。我们能够成功验证策略中的令牌。以下是 APIM xml 政策。

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Invalid or Expired token" require-expiration-time="true" require-signed-tokens="true">
 <openid-config url="https://login.microsoftonline.com/tenantid/v2.0/.well-known/openid-configuration" />
                <audiences>
                    <audience>https://management.azure.com</audience>
                </audiences>
                <issuers>
                    <issuer>https://sts.windows.net/tenantid/</issuer>
                </issuers>
                <required-claims>
                    <claim name="oid" match="any">
                        <value>objectid of the managed identity/system assigned</value>
                    </claim>
                </required-claims>
            </validate-jwt>

现在我们已经分配了用户管理的身份并使用以下代码将身份分配给函数应用程序,我能够生成令牌,但在 APIM 中它抛出了奇怪的错误。

var azureServiceTokenProvider = new ManagedIdentityCredential(clientId: "client-id-of-managed-identity-id");
accessToken = await azureServiceTokenProvider.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] { "https://management.azure.com" + "/.default" }));

APIM 告诉我们

“JWT 验证失败:IDX10501:签名验证失败。无法匹配密钥:\nkid:''。\n捕获的异常:\n ''。

关于如何克服这个问题的任何想法?

【问题讨论】:

  • 是的,我没有使用托管身份,而是通过传递客户端 ID 来使用 defaultcredential 选项。
  • 您可以将其添加为答案并接受它,以便对可能面临相同问题的其他社区成员有所帮助。

标签: jwt azure-functions azure-api-management azure-managed-identity azure-identity


【解决方案1】:

我已更新我的代码以使用 DefaultAzureCredential 而不是 ManagedIdentityCredential 并且它开始工作了。

var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions
                { ManagedIdentityClientId = "managed_identity_clinet_id" });
AccessToken accessToken = await credential.GetTokenAsync(
                    new TokenRequestContext(scopes: new string[] { "https://management.azure.com" + "/.default" }) { });

我传递了托管身份的客户端 ID,并且能够继续使用生成的令牌。

【讨论】:

    猜你喜欢
    • 2022-06-18
    • 2020-11-22
    • 2021-10-12
    • 2015-06-24
    • 2017-10-22
    • 1970-01-01
    • 2021-03-21
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多