Tuesday, June 27, 2023

Azure API Management: Setting secret from Azure Key Vault in header policies

Credits: Accessing Azure Key Vault from within Azure API Management | Vincent-Philippe Lauzon’s (vincentlauzon.com)


This article is an extension to what has been talked about in the above post. The code snippet to read Azure Key Vault Secret to set <set-header> under <inbound> <policies> in Azure API Management along with caching the secret for 60 secs has been given below




Code-Snippet for copy paste:

<policies>

    <inbound>

        <base />

        <!--Look for secret in the cache -->

        <cache-lookup-value key="cached-user-secret" variable-name="cached-user-secret" />

        <!-- If API Management doesn’t find it in the cache, fetch it from Key Vault -->

        <choose>

            <when condition="@(!context.Variables.ContainsKey("cached-user-secret"))">

                <!-- Retrieve secret from Key Vault -->

                <send-request mode="new" response-variable-name="cached-user-secret" timeout="20" ignore-error="false">

                    <set-url>https://{{kvname}}.vault.azure.net//secrets/{{secret-name}}/?api-version=7.0</set-url>

                    <set-method>GET</set-method>

                    <authentication-managed-identity resource="https://vault.azure.net" />

                </send-request>

                <!-- Store response body in context variable as a string -->

                <set-variable name="cached-user-secret" value="@((((IResponse)context.Variables["cached-user-secret"]).Body.As<JObject>()).Property("value").Value.ToString())" />

                <!-- Store result in cache -->

                <cache-store-value key="cached-user-secret" value="@((string)context.Variables["cached-user-secret"])" duration="60" />

            </when>

        </choose>

                <set-header name="User-secret" exists-action="append">

            <value>@((string)context.Variables["cached-user-secret"])</value>

        </set-header>

    </inbound>

    <backend>

        <base />

    </backend>

    <outbound>

        <base />

    </outbound>

    <on-error>

        <base />

    </on-error>

</policies>


Performance numbers:

Inbound (268+ ms) - 1st time

api-inspector (0.259ms)

api-inspector (0.003ms)

cors (0.024ms)

cache-lookup-value (0.006ms)

cache-lookup-value (0.934ms)

choose (0.024ms)

set-method (0.025ms)

authentication-managed-identity (0.253ms)

authentication-managed-identity (0.005ms)

send-request (0.078ms)

send-request (267.616ms) -> Key Vault call for User Secret

send-request (0.034ms)

response-variable-handler (0.010ms)

response-variable-handler (11.223ms)

set-variable (0.118ms)

set-variable (0.014ms)

cache-store-value (0.005ms)

cache-store-value (0.065ms)

                cache-store-value (0.087ms)


From 2nd time onwards, it is only few ms