public async Task <string> ReadOrRetrieveAccessToken <ServiceAgentSettings>(ServiceAgentSettings settings) where ServiceAgentSettings : OAuthAgentSettingsBase { var cacheKey = $"{settings.OAuthClientId}{settings.OAuthClientSecret}{settings.OAuthScope}{settings.OAuthTokenEndpoint}"; var(succeeded, tokenReplyResult) = await _cacher.GetFromCacheAsync <TokenReply>(cacheKey).ConfigureAwait(false); if (!succeeded || tokenReplyResult == null) { tokenReplyResult = await RetrieveTokenReply(settings.OAuthClientId, settings.OAuthClientSecret, settings.OAuthScope, settings.OAuthTokenEndpoint); if (tokenReplyResult == null) { throw new Exception($"Unable to retrieve token reply for agent with key {cacheKey}"); } int cacheExpiration = CalculateCacheExpiration(tokenReplyResult); if (cacheExpiration > 0) { await _cacher.SaveToCacheAsync(cacheKey, tokenReplyResult); } } return(tokenReplyResult.access_token); }