0

In APIM I want to get an OAuth token before calling the back-end and store it in the APIM cache.

I manage to get the OAuth token.

I wish to store my token in the cache for this I need a duration. Extracting the duration from the response body is my issue.

First I extract the token and duration to save these in variables. Then the variables are used to store a value in the cache.

When extracting the integer value of "expires_in" it fails.

Response object:

{
    "access_token": "accesstokenresponse",
    "token_type": "bearer",
    "expires_in": 3600
}

extracting data and put in variables:

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

<set-variable name="expires-in" 
    value="@(((IResponse)context.Variables["response"]).Body.As<JObject>(preserveContent: true)["expires_in"].ToString())" />

storing in cache:

<cache-store-value key="OAuthKey" 
    value="@((string)context.Variables["bearer-token"])"
    duration="@((int)context.Variables["expires-in"])" />

Extracting the "expires_in" results in an Object reference not set to an instance of an object.

set-variable (153.612 ms)
{
    "messages": [
        {
            "message": "Expression evaluation failed.",
            "expression": "((IResponse)context.Variables[\"response\"]).Body.As<JObject>(preserveContent: true)[\"expires_in\"].ToString()",
            "details": "Object reference not set to an instance of an object."
        },
        "Expression evaluation failed. Object reference not set to an instance of an object.",
        "Object reference not set to an instance of an object."
    ]
}
Kalana
  • 5,631
  • 7
  • 30
  • 51
PR33T0
  • 15
  • 5

1 Answers1

2

Try to maintain the value of Objects using (preserveContent: true) on first line as well, thus:

value="@(((IResponse)context.Variables["response"]).Body.As<JObject>(preserveContent:true)["access_token"].ToString())" />

Let me know if it's solved.

Kalana
  • 5,631
  • 7
  • 30
  • 51
Edifirst
  • 88
  • 5
  • 1
    In addition to that you also need to get value as int. Right now you get it as string (.ToString call), but then cast this variable to int. Try getting it as int int the first place: (int)(...["expires-in]) – Vitaliy Kurokhtin Sep 21 '19 at 15:37