Share via

Exception thrown while using caching in apim

Sanjana Pushkar 201 Reputation points Microsoft Employee
2023-09-05T15:18:52.46+00:00

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?

User's image

User's image

Any help is appreciated. Thanks!

Azure API Management
Azure API Management

An Azure service that provides a hybrid, multi-cloud management platform for APIs.

0 comments No comments

Answer accepted by question author

Thomas Meads 1,586 Reputation points
2023-09-05T17:22:43.75+00:00

Hi,

I believe the error is coming from your return response when your have fetched the token. You have this code:

<choose>
	<when condition="@(!context.Variables.ContainsKey("cache-access-token"))">
		...
		<set-body>
			@{ 
				var response = (string)context.Variables["cache-access-token"];        
				return response;
			}
		</set-body>
		...
	</when>
</choose>

However at this point in your code you do not have the cache-access-token set in variables. This is because you have set it in the cache but not retrieved it again. The best fix would be to change the above code to:

<set-body>	
	@{ 		
		var response = (string)context.Variables["accessToken"];        		
		return response;	
	}
</set-body>

I would advise that you look at API Authorisations as I believe it may meet your needs for this policy: https://learn.microsoft.com/en-us/azure/api-management/authorizations-overview

Hope this helps

Was this answer helpful?

2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.