Wednesday, January 16, 2019

how to improve the Azure web api call with Token Cache?

if you develop an application with heavy traffic to Azure web api. you should have the cache mechanism to reduce the around trip for token, usually the token will not expire in short peroid.


here i will show a trick to cache the Azure Token with the Token Cache from .net framework.


 private static async Task<string> GetAzureTokenFromCache(string resourceUrl, string clientId, string clientKey) {
            string token = string.Empty;
            if (tokenCache.Count > 0)
            {
                System.Collections.Generic.IEnumerable<TokenCacheItem> List = tokenCache.ReadItems();

                foreach (var value in List)
                {
                
                         if (value.ExpiresOn < DateTime.UtcNow.AddMinutes(60) || String.IsNullOrEmpty(value.AccessToken) || !IsJwtTokenValid(value.AccessToken))
                        {
                            tokenCache.DeleteItem(value);
                            token = await GetAzureToken(resourceUrl,clientId, clientKey);
                        }
                        else
                            token = value.AccessToken;
                    }
                }
                if (String.IsNullOrEmpty(token)) {
                    token = await GetAzureToken(resourceUrl, clientId, clientKey);
                }
            return token;
        }

        private static async Task<string> GetAzureToken(string resourceUrl,string clientId, string key)
        {
            ClientCredential clientCred = new ClientCredential(clientId, key);
            AuthenticationContext authContext = null;
            AuthenticationResult result = null;
            authContext = new AuthenticationContext("https://login.microsoftonline.com/scimdm.onmicrosoft.com",false, tokenCache);
            result = await authContext.AcquireTokenAsync(resourceUrl, clientCred);
                return result.AccessToken ?? "";
            }
        }

1 comment:

  1. Nice blog here! Also your web site loads up fast! What host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

    ReplyDelete