How to access a <send-request> reponse variable in azure apim policies

Hendriks, Hugo 20 Reputation points
2024-05-02T08:07:33.0066667+00:00

I am trying to add a oauth2 callout to my azure apim policy. I do a <send-request>

<send-request mode="new" response-variable-name="tokenResponse" timeout="20" ignore-error="false">
            <set-url>{{oauth2-token-url}}</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 "grant_type=client_credentials&amp;client_id={{oauth2-client-id}}&amp;client_secret={{oauth2-client-secret}}";}</set-body>
        </send-request>


This callout works. Next i want to store the accessToken which is located in the tokenResponse but I can't get the variable to work. I am trying to cast it like:

<set-variable name="accessToken" value="@(((IResponse)context.Variables["tokenResponse"]).Body.As<JObject>()).SelectToken("access_token").ToString()" />

but this doesn't seem to work. Can anyone elaborate on this. How do I cast from Microsoft.WindowsAzure.ApiManagement.Proxy.Gateway.PipelineResponse to a JSON object and retrieve the access_token property.

Thanks in advance!

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
1,825 questions
Azure Policy
Azure Policy
An Azure service that is used to implement corporate governance and standards at scale for Azure resources.
808 questions
0 comments No comments
{count} votes

Accepted answer
  1. JananiRamesh-MSFT 22,221 Reputation points
    2024-05-02T09:20:15.78+00:00

    @Hendriks, Hugo Thanks for reaching out. Could you please try the below?

    
    <set-variable name="accessToken" value="@((String)((IResponse)context.Variables["tokenResponse"]).Body.As<JObject>()["access_token"])" />
    
    <set-header name="Authorization" exists-action="override">
     <value>
            @("Bearer " + (String)((IResponse)context.Variables["bearerToken"]).Body.As<JObject>()["access_token"])
     </value>
    </set-header>
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Hendriks, Hugo 20 Reputation points
    2024-05-02T09:18:16.0266667+00:00

    Found the answer....this did the trick for me:

    <set-variable name="accessToken" value="@(((IResponse)context.Variables["tokenResponse"]).Body.As<JObject>()["access_token"].ToString())" />