Hi,
I have a OAuth implemented inside my apim, i am using caching so it doesn't hit the backend as the token has a validity of 7200s. Below is the policy that i have added:
<set-variable name="concatenated" value="@($"{context.Variables["Client-Id"]}:{context.Variables["Client-Secret"]}")" />
<cache-lookup-value key="@("token-" + context.Variables["Client-Id"])" variable-name="cache-access-token" />
<choose>
<when condition="@(!context.Variables.ContainsKey("cache-access-token"))">
<send-request ignore-error="false" timeout="20" response-variable-name="accessTokenResponse" mode="copy">
<set-url>http://OAuthurl.com</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-header name="Authorization" exists-action="override">
<value>@("Basic " + System.Convert.ToBase64String(Encoding.UTF8.GetBytes((string)context.Variables["concatenated"])))</value>
</set-header>
<set-body>@($"grant_type=value1&scope=value2")</set-body>
</send-request>
<set-variable name="accessToken" value="@((string)((IResponse)context.Variables["accessTokenResponse"]).Body.As<JObject>()["access_token"])" />
<cache-store-value key="@("token-" + context.Variables["Client-Id"])" value="@((string)context.Variables["accessToken"])" duration="7200" />
<return-response>
<set-status code="200" reason="OK" />
<set-body>@{ var response = (string)context.Variables["cache-access-token"];
return response;
}</set-body>
</return-response>
</when>
<otherwise>
<return-response>
<set-status code="200" reason="OK" />
<set-body>@{ var response = (string)context.Variables["cache-access-token"];
return response;
}</set-body>
</return-response>
</otherwise>
</choose>
So i am calling the apim from from function app to receive the token value in response, the policy works fine as long as the cache value is being returned, but when the token expires and it calls the backend again, I am getting the below error, and when I hit it again, the apim returns the new token value without an error.
Seems weird to me, does anyone have an idea why this is happening?


Any help is appreciated. Thanks!