Exemplo n.º 1
0
        /// <summary>
        /// Requests access token for current region from token api.
        /// </summary>
        /// <param name="region"></param>
        /// <returns></returns>
        private async Task <Token> RequestTokenAsync(RegionEnum region)
        {
            // Request new token if token is not cached
            var token = await _cache.GetOrAddAsync($"token-{region.ToQueryString()}", async q =>
            {
                // Build token request parameters
                var content = new FormUrlEncodedContent(new List <KeyValuePair <string, string> > {
                    new KeyValuePair <string, string>("grant_type", "client_credentials")
                });

                // Setup client credentials authorization
                _tokenClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                                                                                                 Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_defaultApiConfiguration.ClientId}:{_defaultApiConfiguration.ClientSecret}"))
                                                                                                 );

                using var response = await _tokenClient.PostAsync(_defaultApiConfiguration.GetTokenApiUrl(region), content);
                response.EnsureSuccessStatusCode();

                var tokenJson   = await response.Content.ReadAsStringAsync();
                var tokenObject = JsonConvert.DeserializeObject <Token>(tokenJson);

                q.SetAbsoluteExpiration(TimeSpan.FromSeconds(tokenObject.Expiration));

                return(tokenObject);
            });

            return(token);
        }