protected async Task EnsureAccessTokenAsync(bool forceRefresh = false) { var cacheKey = $"identity:accesstoken:{_clientKey}"; if (forceRefresh || !_cache.TryGetValue <AccessToken>(cacheKey, out var accessToken)) { accessToken = await _accessTokenProvider.RequestAccessTokenAsync().ConfigureAwait(false); var cacheEntryOptions = new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(accessToken.ExpiryDurationSecs - 300) }; _cache.Set(cacheKey, accessToken, cacheEntryOptions); } HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken.Token); }
public async Task <RestClient> CreateWithAuthorizationHeader(string baseUrl, string accessTokenKey) { var client = new RestClient { BaseUrl = new Uri(baseUrl) }; if (!_cache.TryGetValue <AccessToken>(accessTokenKey, out var accessToken)) { accessToken = await _accessTokenProvider.RequestAccessTokenAsync(); var expirySecs = Math.Max(accessToken.ExpiryDurationSecs - ExpiryBufferSecs, 0); var cacheEntryOptions = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(expirySecs) }; _cache.Set(accessTokenKey, accessToken, cacheEntryOptions); } client.AddDefaultHeader("Authorization", $"Bearer {accessToken.Token}"); return(client); }