public async Task <IDevOpsVaultClient> GetClient(DevOpsVaultContext context)
        {
            bool needsRefresh = true;

            var config = new Configuration
            {
                BasePath = BuildTenantUri(context.DevOpsVaultUrl.AbsoluteUri), Timeout = 2000
            };

            GlobalConfiguration.Instance = Configuration.MergeConfigurations(GlobalConfiguration.Instance, config);

            if (TokenCache.ContainsKey(context.ClientId))
            {
                var timeToRefresh = TokenCache[context.ClientId].ExpirationTime.AddMinutes(-10);
                if (timeToRefresh > DateTime.UtcNow)
                {
                    needsRefresh = false;
                }
            }

            if (needsRefresh)
            {
                var tokensApi = _apiClientFactory.GetTokensApi();

                var response = await tokensApi.TokenAsync("client_credentials", clientId : context.ClientId,
                                                          clientSecret : context.ClientSecret);

                if (response == null || string.IsNullOrEmpty(response.AccessToken))
                {
                    throw new SecureStoreException(SecureStoreException.Type.InvalidConfiguration,
                                                   DevOpsVaultResource.GetResource("UnableToAuthenticate"));
                }

                TokenCache[context.ClientId] = new AccessTokenInfo
                {
                    AccessToken    = response.AccessToken,
                    ExpirationTime = DateTime.UtcNow.AddSeconds(response.ExpiresIn)
                };
            }

            config.AccessToken = TokenCache[context.ClientId].AccessToken;

            GlobalConfiguration.Instance = Configuration.MergeConfigurations(GlobalConfiguration.Instance, config);
            var secretsApi = _apiClientFactory.GetSecretsApi();

            return(new DevOpsVaultClient(secretsApi, context));
        }
Example #2
0
 public DevOpsVaultClient(ISecretsApi secretsClient, DevOpsVaultContext context)
 {
     _secretsClient = secretsClient;
     _context       = context;
 }