public void TestInitialize()
 {
     _tokensApi        = Substitute.For <ITokensApi>();
     _secretsApi       = Substitute.For <ISecretsApi>();
     _apiClientFactory = Substitute.For <IDevOpsVaultApiClientFactory>();
     _apiClientFactory.GetTokensApi().Returns(_tokensApi);
     _apiClientFactory.GetSecretsApi().Returns(_secretsApi);
     _clientFactory = new DevOpsVaultClientFactory(_apiClientFactory);
     _secureStore   = new DevOpsVaultSecureStore(_clientFactory);
     _devOpsContext = new DevOpsVaultContext();
     _devOpsContext.BasePathPrefix = "uipath";
     _devOpsContext.DevOpsVaultUrl = new Uri("https://test.secretsvault.fake");
     _devOpsContext.ClientId       = "test-client";
     _devOpsContext.ClientSecret   = "test-secret";
     _ctxString = JsonConvert.SerializeObject(_devOpsContext);
 }
        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));
        }