Skip to content

Instantly share code, notes, and snippets.

@rupertbenbrook
Last active May 3, 2021 19:42
Show Gist options
  • Save rupertbenbrook/cd79614692c3d2daa2e18cb90915fb68 to your computer and use it in GitHub Desktop.
Save rupertbenbrook/cd79614692c3d2daa2e18cb90915fb68 to your computer and use it in GitHub Desktop.
Azure API Management inbound policy for backend OAuth2 client credentials flow with token caching
<!--
This relies on a number of properties being defined in API Management:
• EnableCache – Either “true” or “false”. This is used to enable and disable caching of tokens.
• OAuth2TokenEndpoint – The AAD OAuth2 token endpoint URI to get a token from. It takes the form https://login.microsoftonline.com/<subscription-guid>/oauth2/token.
• OAuth2ClientCredentials – The client ID GUID of the AAD application registered for the API Management server to authenticate.
• OAuth2ClientSecret – The client secret key generated for the AAD application registered for the API Management server.
• OAuth2Resource – The application ID URI for the application whose API is being accessed, and who is enabled for delegation in the AAD application registered for the API Management server.
-->
<inbound>
<choose>
<when condition="@("{{EnableCache}}" == "true")">
<cache-lookup-value key="cache_oauth2_access_token" default-value="empty" variable-name="access_token" />
</when>
<otherwise>
<set-variable name="access_token" value="empty" />
</otherwise>
</choose>
<choose>
<when condition="@(((string)context.Variables["access_token"]) == "empty")">
<send-request mode="new" response-variable-name="token" timeout="10" ignore-error="false">
<set-url>{{OAuth2TokenEndpoint}}</set-url>
<set-method>POST</set-method>
<set-header name="Content-Type" exists-action="override">
<value>application/x-www-form-urlencoded</value>
</set-header>
<set-body>grant_type=client_credentials&amp;client_id={{OAuth2ClientCredentials}}&amp;client_secret={{OAuth2ClientSecret}}&amp;resource={{OAuth2Resource}}</set-body>
</send-request>
<set-variable name="response" value="@(((IResponse)context.Variables["token"]).Body.As<JObject>())" />
<set-variable name="access_token" value="@(((JObject)context.Variables["response"]).GetValue("access_token").ToString())" />
<set-variable name="cache_duration" value="@(int.Parse(((JObject)context.Variables["response"]).GetValue("expires_in").ToString()) / 2)" />
<cache-store-value key="cache_oauth2_access_token" value="@((string)context.Variables["access_token"])" duration="@((int)context.Variables["cache_duration"])" />
</when>
</choose>
<set-header name="Authorization" exists-action="override">
<value>@($"Bearer {context.Variables["access_token"]}")</value>
</set-header>
</inbound>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment