APIM Policy to Retrieve D365 Bearer Token

APIM Policy to Retrieve D365 Bearer Token

The policy below adds the “Authorization” header to the backend request.  All token request parameters are added to APIM as Named values.  The “D365-secret” named value points to a secret in the key vault so that it is kept private.  A retry policy is also added in case there is an issue retrieving the bearer token.

<policies>
    <inbound>
        <base />
        <retry condition=“@(context.Variables[“bearerToken“] == null ||
((IResponse)context.Variables[“bearerToken”]).StatusCode >= 500)”
count=”5″ interval=”10″ max-interval=”50″ delta=”10″ first-fast-retry=”true”>
            <send-request mode=“new” response-variable-name=“bearerToken” timeout=“20” ignore-error=“true”>
                <set-url>https://login.microsoftonline.com/{{d365-tenantid}}/oauth2/token</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>@{
return
“client_id={{d365-clientid}}&resource={{d365-resource-dmf}}&client_secret={{d365-secret}}&grant_type={{d365-granttype}}”;
           }</set-body>
            </send-request>
        </retry>
        <set-header name=“Authorization” exists-action=“override”>
            <value>
@(“Bearer ” + (String)((IResponse)context.Variables[“bearerToken”]).Body.As<JObject>()[“access_token”])
            </value>
        </set-header>
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Leave a Reply

Your email address will not be published. Required fields are marked *