xmlazure-api-managementpolicyapim

Azure APIm Caching throwing 500


I have an APIm fragment that validates an Entra ID OAuth 2 token, and then obtains a third party token from an external IdP, to securely call a backend service. I was hoping to cache the the third party token using cache-lookup-value and cache-store-value - however this is causing APIm to throw a 500. I cannot run trace through Azure console, the problem seems to be fairly low level. Any thoughts on wht might be wrong would be gratefully received.

The full fragment is extracted below and is parsed correctly in the APIm fragment editor.

Cheers, Andrew

<fragment>
    <set-variable name="clientID" value="{{essential-client-id}}" />
    <set-variable name="clientSecret" value="{{essential-client-secret}}" />
    <base />
    <validate-azure-ad-token tenant-id="{{essential-api-tenant-id}}" output-token-variable-name="jwt" failed-validation-error-message="Missing Entra ID OAuth 2.0 token">
        <client-application-ids>
            <application-id>{{mg4v-application-id}}</application-id>
        </client-application-ids>
        <audiences>
            <audience>api://{{essential-api-application-id}}</audience>
        </audiences>
    </validate-azure-ad-token>
    <cache-lookup-value key="essential-bearer-token" default-value="cache-miss" variable-name="bearerToken" caching-type="internal" />
    <set-variable name="cacheMiss" value="@( ((string)context.Variables["bearerToken"]).Equals("cache-miss") )" />
    <choose>
        <when condition="@(context.Variables.GetValueOrDefault<bool>("cacheMiss"))">
            <!-- If there is no valid cached token then call the Essential IdP to get a new one-->
            <send-request ignore-error="true" timeout="20" response-variable-name="bearerToken" mode="new">
                <set-url>{{essential-api-domain}}/api/oauth/token</set-url>
                <set-method>POST</set-method>
                <set-header name="Content-Type" exists-action="override">
                    <value>application/json</value>
                </set-header>
                <set-header name="x-api-key" exists-action="override">
                    <value>{{essential-api-key}}</value>
                </set-header>
                <!--  We do not want to expose our APIM subscription key to the backend API  -->
                <set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />
                <set-body>@($"{{\"grantType\": \"password\", \"username\": \"{(string)context.Variables["clientID"]}\", \"password\": \"{(string)context.Variables["clientSecret"]}\" }}")</set-body>
            </send-request>
            <!-- Store the new token for 295s-->
            <cache-store-value key="essential-bearer-token" value="@((string)context.Variables["bearerToken"])" duration="295" caching-type="internal" />
        </when>
    </choose>
 </fragment>

Solution

  • Ok, figured out the problem. I was caching the returned IResponse object instead of the enclosed bearerToken string. Working `fragment` below. In general the APIm tracing does not provide much in the way of meaningful error messages

    
    <fragment>
        <set-variable name="clientID" value="{{essential-client-id}}" />
        <set-variable name="clientSecret" value="{{essential-client-secret}}" />
        <set-variable name="bearerToken" value="cache-miss" />
        <validate-azure-ad-token tenant-id="{{essential-api-tenant-id}}" output-token-variable-name="jwt" failed-validation-error-message="Missing Entra ID OAuth 2.0 token">
            <client-application-ids>
                <application-id>{{mg4v-application-id}}</application-id>
            </client-application-ids>
            <audiences>
                <audience>api://{{essential-api-application-id}}</audience>
            </audiences>
        </validate-azure-ad-token>
        <cache-lookup-value key="essential-bearer-token" default-value="cache-miss" variable-name="bearerToken" caching-type="internal" />
        <set-variable name="cacheMiss" value="@( ((string)context.Variables["bearerToken"]).Equals("cache-miss") )" />
        <!-- If there is no valid cached token then call the Essential IdP to get a new one-->
        <!-- Store the new token for 295s-->
        <choose>
            <when condition="@(context.Variables.GetValueOrDefault<bool>("cacheMiss"))">
                <send-request ignore-error="true" timeout="20" response-variable-name="oauthToken" mode="new">
                    <set-url>{{essential-api-domain}}/api/oauth/token</set-url>
                    <set-method>POST</set-method>
                    <set-header name="Content-Type" exists-action="override">
                        <value>application/json</value>
                    </set-header>
                    <set-header name="x-api-key" exists-action="override">
                        <value>{{essential-api-key}}</value>
                    </set-header>
                    <!--  We do not want to expose our APIM subscription key to the backend API  -->
                    <set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />
                    <set-body>@($"{{\"grantType\": \"password\", \"username\": \"{(string)context.Variables["clientID"]}\", \"password\": \"{(string)context.Variables["clientSecret"]}\" }}")</set-body>
                </send-request>
                <cache-store-value key="essential-bearer-token" value="@($"Bearer {(String)((IResponse)context.Variables["oauthToken"]).Body.As<JObject>().SelectToken("bearerToken")}")" duration="295" caching-type="internal" />
            </when>
        </choose>
     </fragment>