Showing posts with label APIM Policy. Show all posts
Showing posts with label APIM Policy. Show all posts

Wednesday, October 27, 2021

Authenticate Azure APIM using Managed Identity to access Storage Account

<policies>
<inbound>
<!-- check the cache for secret first -->
<cache-lookup-value key="mysecret" variable-name="keyvaultsecretResponse" />
<!-- call Key Vault if not found in cache -->
<choose>
<when condition="@(!context.Variables.ContainsKey("keyvaultsecretResponse"))">
<send-request mode="new" response-variable-name="keyvaultsecret" timeout="20" ignore-error="false">
<set-url>https://msikvtest.vault.azure.net/secrets/mysecret/?api-version=7.0</set-url>
<set-method>GET</set-method>
<authentication-managed-identity resource="https://vault.azure.net" />
</send-request>
<!-- transform response to string and store in cache -->
<set-variable name="keyvaultsecretResponse" value="@(((IResponse)context.Variables["keyvaultsecret"]).Body.As<string>())" />
<cache-store-value key="mysecret" value="@((string)context.Variables["keyvaultsecretResponse"])" duration="3600" />
</when>
</choose>
<return-response>
<set-status code="200" reason="Done" />
<set-header name="content-type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@((string)context.Variables["keyvaultsecretResponse"])</set-body>
</return-response>
<base />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>