示例#1
0
        /// <summary>
        /// Delete a secret from Key Vault
        /// </summary>
        /// <param name="keyvaultName">ID of the secret</param>
        /// <returns>keyName that was deleted</returns>
        public async Task <string> DeleteSecretAsync(string keyvaultName, string keyName)
        {
            var secretUrl = GetKeyVaultSecretUrl(keyvaultName);
            var secret    = await _keyVaultClient.DeleteSecretAsync(secretUrl, keyName);

            return(keyName);
        }
示例#2
0
        public async Task <DeletedSecretBundle> DeleteSecret(string secretName)
        {
            var client = new KeyVaultClient(AuthCallback);
            var r      = await client.DeleteSecretAsync(VaultBaseUrl, secretName);

            return(r);
        }
示例#3
0
 private async Task ClearAllKeyVaultSecrets()
 {
     foreach (SecretItem item in await KeyVaultClient.GetSecretsAsync(GetKeyVaultBaseUrl()))
     {
         await KeyVaultClient.DeleteSecretAsync(GetKeyVaultBaseUrl(), item.Identifier.Name);
     }
 }
示例#4
0
        /// <summary>
        /// Creates a secret in Azure Key Vault and returns its ID.
        /// </summary>
        /// <param name="secretName">The name of the secret to create.</param>
        /// <returns>The ID of the secret created.</returns>
        public static string SetUpKeyVaultSecret(string secretName)
        {
            KeyVaultClient cloudVault = new KeyVaultClient(GetAccessToken);
            string         vaultUri   = CloudConfigurationManager.GetSetting("VaultUri");

            try
            {
                // Delete the secret if it exists.
                cloudVault.DeleteSecretAsync(vaultUri, secretName).GetAwaiter().GetResult();
            }
            catch (KeyVaultClientException ex)
            {
                if (ex.Status != System.Net.HttpStatusCode.NotFound)
                {
                    Console.WriteLine("Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
                    Console.WriteLine("Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
                    Console.WriteLine("Press any key to exit");
                    Console.ReadLine();
                    throw;
                }
            }

            // Create a 256bit symmetric key and convert it to Base64.
            SymmetricKey symmetricKey   = new SymmetricKey(secretName, SymmetricKey.KeySize256);
            string       symmetricBytes = Convert.ToBase64String(symmetricKey.Key);

            // Store the Base64 of the key in the key vault. Note that the content-type of the secret must
            // be application/octet-stream or the KeyVaultKeyResolver will not load it as a key.
            Secret cloudSecret = cloudVault.SetSecretAsync(vaultUri, secretName, symmetricBytes, null, "application/octet-stream").GetAwaiter().GetResult();

            // Return the base identifier of the secret. This will be resolved to the current version of the secret.
            return(cloudSecret.SecretIdentifier.BaseIdentifier);
        }
        /// <summary>
        /// Creates a secret in Azure Key Vault and returns its ID.
        /// </summary>
        /// <param name="secretName">The name of the secret to create.</param>
        /// <returns>The ID of the secret created.</returns>
        public static string SetUpKeyVaultSecret(string secretName)
        {
            KeyVaultClient cloudVault = new KeyVaultClient(GetAccessToken);
            string vaultUri = CloudConfigurationManager.GetSetting("VaultUri");

            try
            {
                // Delete the secret if it exists.
                cloudVault.DeleteSecretAsync(vaultUri, secretName).GetAwaiter().GetResult();
            }
            catch (KeyVaultClientException ex)
            {
                if (ex.Status != System.Net.HttpStatusCode.NotFound)
                {
                    Console.WriteLine("Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
                    Console.WriteLine("Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
                    Console.WriteLine("Press any key to exit");
                    Console.ReadLine();
                    throw;
                }
            }

            // Create a 256bit symmetric key and convert it to Base64.
            SymmetricKey symmetricKey = new SymmetricKey(secretName, SymmetricKey.KeySize256);
            string symmetricBytes = Convert.ToBase64String(symmetricKey.Key);

            // Store the Base64 of the key in the key vault. Note that the content-type of the secret must
            // be application/octet-stream or the KeyVaultKeyResolver will not load it as a key.
            Secret cloudSecret = cloudVault.SetSecretAsync(vaultUri, secretName, symmetricBytes, null, "application/octet-stream").GetAwaiter().GetResult();

            // Return the base identifier of the secret. This will be resolved to the current version of the secret.
            return cloudSecret.SecretIdentifier.BaseIdentifier;
        }
        public async Task DeleteSecretAsync(Guid subscriptionId, KeyVault keyVault, string secretName)
        {
            // Authenticate using MSI
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://vault.azure.net");

            var token          = new TokenCredentials(accessToken);
            var keyVaultClient = new KeyVaultClient(token);

            try
            {
                await keyVaultClient.DeleteSecretAsync(keyVault.Uri, secretName);
            }
            catch (KeyVaultErrorException ex)
            {
                if (ex.Body.Error.Code != "SecretNotFound")
                {
                    throw new Exception($"Failed to set secret with principal: {azureServiceTokenProvider.PrincipalUsed}", ex);
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to set secret with principal: {azureServiceTokenProvider.PrincipalUsed}", e);
            }
        }
示例#7
0
        public async Task DeleteSecretAsync(string key)
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            using var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            if (_configuration[key] == null)
            {
                return;
            }

            // Delete the secret in the key vault
            //
            try
            {
                await keyVaultClient.DeleteSecretAsync(KeyVaultEndpoint, key);
            }
            catch (KeyVaultErrorException ex)
            {
                Console.WriteLine("\n\nError:" + ex.Message);
            }

            // Delete it locally (needed in case the secret cannot be deleted). If the above statement fails, this will save it.
            // Without this, the user may have an invalid refresh token stored in the key vault and can't use the bot anymore.
            //
            _configuration[key] = null;

            // Reload the configuration because we added a new secret
            ((IConfigurationRoot)_configuration).Reload();
        }
示例#8
0
 public void Write(string key, string value)
 {
     if (value == null)
     {
         _vaultClient.DeleteSecretAsync(_vaultUri, key);
     }
     else
     {
         _vaultClient.SetSecretAsync(_vaultUri, key, value).Wait();
     }
 }
示例#9
0
            private async Task ClearAllKeyVaultSecrets()
            {
                var secretsPages = await KeyVaultSecretsRepository.GetKeyVaultSecretsPagesAsync(KeyVaultClient, GetKeyVaultBaseUrl());

                foreach (IPage <SecretItem> secretsPage in secretsPages)
                {
                    foreach (SecretItem item in secretsPage)
                    {
                        await KeyVaultClient.DeleteSecretAsync(GetKeyVaultBaseUrl(), item.Identifier.Name);
                    }
                }
            }
示例#10
0
        /// <summary>
        /// Deletes the specified identifier from the vault.
        /// </summary>
        /// <param name="identifier">Identifier of the entity to be deleted.</param>
        /// <returns>An instance of <see cref="Task"/> that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentException">
        /// <paramref name="identifier"/> is empty or null.
        /// </exception>
        public async Task DeleteAsync(string identifier)
        {
            DateTime startTime;
            Dictionary <string, double> eventMetrics;
            Dictionary <string, string> eventProperties;

            identifier.AssertNotEmpty(nameof(identifier));

            try
            {
                startTime = DateTime.Now;

                if (!IsEnabled)
                {
                    return;
                }

                using (IKeyVaultClient client = new KeyVaultClient(service.TokenManagement.GetAppOnlyTokenAsync))
                {
                    try
                    {
                        await client.DeleteSecretAsync(service.Configuration.KeyVaultBaseAddress, identifier);
                    }
                    catch (KeyVaultErrorException ex)
                    {
                        if (!ex.Body.Error.Code.Equals(NotFoundErrorCode, StringComparison.CurrentCultureIgnoreCase))
                        {
                            throw;
                        }
                    }
                }

                // Track the event measurements for analysis.
                eventMetrics = new Dictionary <string, double>
                {
                    { "ElapsedMilliseconds", DateTime.Now.Subtract(startTime).TotalMilliseconds }
                };

                // Capture the request for the customer summary for analysis.
                eventProperties = new Dictionary <string, string>
                {
                    { "Identifier", identifier }
                };

                service.Telemetry.TrackEvent("Vault/DeleteAsync", eventProperties, eventMetrics);
            }
            finally
            {
                eventMetrics    = null;
                eventProperties = null;
            }
        }
示例#11
0
        public async Task <string> DeleteSecretAsync(string secretName)
        {
            if (string.IsNullOrEmpty(secretName))
            {
                throw new ArgumentNullException("secretName");
            }
            // KeyVault doesn't allow dots in key name, allows only alphanumeric and dashes. Replace dots with dash
            string fixedSecretName = FixSecretName(secretName);

            var deletedSecretResult = await _keyVaultClient.DeleteSecretAsync(_keyVaultUrl, fixedSecretName);

            return(deletedSecretResult.Value);
        }
        public async Task <string> DeleteSecretAsyn(string name)
        {
            try
            {
                var response = await _keyVaultClient.DeleteSecretAsync(_kvUri, name);

                return(response.Id);
            }
            catch (KeyVaultErrorException e)
            {
                Log.Error("Failed to delete the secret.", e);
                throw;
            }
        }
示例#13
0
 private Task DeleteSecretAsync(string secret)
 {
     return(Task.Run(async() =>
     {
         try
         {
             await Client.DeleteSecretAsync(KeyVaultUrl, secret);
         }
         catch (Exception ex)
         {
             EventManager.KeyVaultFailed("DeleteSecretAsync", ex);
         }
     }));
 }
示例#14
0
        /// <summary>
        /// Deletes secret
        /// </summary>
        /// <param name="secretName"> The secret name</param>
        /// <returns> The deleted secret </returns>
        private static SecretBundle DeleteSecret(string secretName)
        {
            // If the secret is not initialized get the secret Id from args
            var vaultAddress = inputValidator.GetVaultAddress();

            secretName = (secretName == string.Empty) ? inputValidator.GetSecretName() : secretName;

            var secret = keyVaultClient.DeleteSecretAsync(vaultAddress, secretName).GetAwaiter().GetResult();

            Console.Out.WriteLine("Deleted secret:---------------");
            PrintoutSecret(secret);

            return(secret);
        }
示例#15
0
        /// <summary>
        /// Delete a secret from Key Vault
        /// </summary>
        /// <param name="keyvaultName">ID of the secret</param>
        /// <returns>secret value</returns>
        public async Task <ApiResult> DeleteSecretAsync(string keyvaultName, string keyName)
        {
            try
            {
                var secretUrl = GetKeyVaultSecretUrl(keyvaultName);

                var secret = await _keyVaultClient.DeleteSecretAsync(secretUrl, keyName);

                return(ApiResult.CreateSuccess("Deleted"));
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#16
0
        public async Task <bool> DeleteSecret(string secretName)
        {
            try
            {
                var keyVaultClient = new KeyVaultClient(AuthenticateVault);
                await keyVaultClient.DeleteSecretAsync(_vaultBaseUrl, secretName);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error deleting secret: " + e);
                return(false);
            }
        }
示例#17
0
        public async Task DeleteAsync(int id)
        {
            // Get list of all items
            var items = await ReadAllAsync();

            // Get item to delete
            var deletedItem = items.Single(c => c.Id == id);

            // Remove item from list
            items.Remove(deletedItem);

            // Update liad cache, no reorder necessary
            _cache.Set("ItemList", items);

            // Remove item from KeyVault
            await keyVaultClient.DeleteSecretAsync(
                KeyVaultBaseUrl, deletedItem.Name);
        }
示例#18
0
 private async Task RemoveConfigAsync(string configName)
 {
     await _client.DeleteSecretAsync(_keyVaultUrl, configName);
 }
 public async Task DeleteSecretAsync(string secretName, CancellationToken cancellationToken = default)
 {
     var keyVaultClient = new KeyVaultClient(GetAccessTokenAsync);
     await keyVaultClient.DeleteSecretAsync(_context.KeyVaultUri.AbsoluteUri, secretName, cancellationToken);
 }
 public SecretBundle DeleteSecret(Uri vaultUri, string secretName)
 {
     return(_keyVaultClient.DeleteSecretAsync(vaultUri.ToString(), secretName).GetAwaiter().GetResult());
 }
示例#21
0
        public ActionResult Index()
        {
            string keyVaultName = "<YOUR_VAULT's_NAME>";
            string vaultBaseURL = $"https://{keyVaultName}.vault.azure.net";


            //Get a token for accessing the Key Vault.
            var azureServiceTokenProvider = new AzureServiceTokenProvider();

            //Create a Key Vault client for accessing the items in the vault;
            var keyVault = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            // Manage secrets in the Key Vault.
            // Create a new secret
            string secretName = "secret-az204";

            Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL,
                                                              secretName,
                                                              "This is a secret testing value")).Wait();
            var secret = Task.Run(async() => await keyVault.GetSecretAsync
                                      ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult();

            // Update an existing secret
            Task.Run(async() => await keyVault.SetSecretAsync(vaultBaseURL,
                                                              secretName,
                                                              "Updated the secret testing value")).Wait();
            secret = Task.Run(async() => await keyVault.GetSecretAsync
                                  ($"{vaultBaseURL}/secrets/{secretName}")).GetAwaiter().GetResult();
            // Delete the secret
            Task.Run(async() => await keyVault.DeleteSecretAsync(vaultBaseURL,
                                                                 secretName)).Wait();

            // Manage certificates in the Key Vault
            string certName = "cert-az204";
            // Create a new self-signed certificate
            var policy = new CertificatePolicy
            {
                IssuerParameters = new IssuerParameters
                {
                    Name = "Self",
                },
                KeyProperties = new KeyProperties
                {
                    Exportable = true,
                    KeySize    = 2048,
                    KeyType    = "RSA"
                },
                SecretProperties = new SecretProperties
                {
                    ContentType = "application/x-pkcs12"
                },
                X509CertificateProperties = new X509CertificateProperties
                {
                    Subject = "CN=AZ204KEYVAULTDEMO"
                }
            };

            Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL,
                                                                      certName, policy, new CertificateAttributes {
                Enabled = true
            })).Wait();
            // When you create a new certificate in the Key Vault it takes some time
            // before it's ready.
            // We added some wait time here for the sake of simplicity.
            Thread.Sleep(10000);
            var certificate = Task.Run(async() => await keyVault.GetCertificateAsync
                                           (vaultBaseURL, certName)).GetAwaiter().GetResult();
            // Update properties associated with the certificate.
            CertificatePolicy updatePolicy = new CertificatePolicy
            {
                X509CertificateProperties = new X509CertificateProperties
                {
                    SubjectAlternativeNames = new SubjectAlternativeNames
                    {
                        DnsNames = new[] { "az204.examref.testing" }
                    }
                }
            };


            Task.Run(async() => await keyVault.UpdateCertificatePolicyAsync(
                         vaultBaseURL, certName, updatePolicy)).Wait();
            Task.Run(async() => await keyVault.CreateCertificateAsync(vaultBaseURL,
                                                                      certName)).Wait();
            Thread.Sleep(10000);


            certificate = Task.Run(async() => await keyVault.GetCertificateAsync(
                                       vaultBaseURL, certName)).
                          GetAwaiter().GetResult();

            Task.Run(async() => await keyVault.UpdateCertificateAsync(certificate.
                                                                      CertificateIdentifier.Identifier, null,
                                                                      new CertificateAttributes
            {
                Enabled =
                    false
            })).Wait();
            Thread.Sleep(10000);

            // Delete the self-signed certificate.
            Task.Run(async() => await keyVault.DeleteCertificateAsync(vaultBaseURL,
                                                                      certName)).Wait();

            // Manage keys in the Key Vault
            string           keyName       = "key-az204";
            NewKeyParameters keyParameters = new NewKeyParameters
            {
                Kty       = "EC",
                CurveName = "SECP256K1",
                KeyOps    = new[] { "sign", "verify" }
            };

            Task.Run(async() => await keyVault.CreateKeyAsync(vaultBaseURL, keyName,
                                                              keyParameters)).Wait();
            var key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL,
                                                                     keyName)).GetAwaiter().GetResult();

            // Update keys in the Key Vault
            Task.Run(async() => await keyVault.UpdateKeyAsync(vaultBaseURL, keyName,
                                                              null, new KeyAttributes
            {
                Expires = DateTime.UtcNow.
                          AddYears(1)
            })).Wait();
            key = Task.Run(async() => await keyVault.GetKeyAsync(vaultBaseURL,
                                                                 keyName)).GetAwaiter().GetResult();

            // Delete keys from the Key Vault
            Task.Run(async() => await keyVault.DeleteKeyAsync(vaultBaseURL, keyName)).
            Wait();


            return(View());
        }
示例#22
0
        public async Task DeleteAsync(IEnumerable <string> fullPaths, CancellationToken cancellationToken = default)
        {
            GenericValidation.CheckBlobFullPaths(fullPaths);

            await Task.WhenAll(fullPaths.Select(fullPath => _vaultClient.DeleteSecretAsync(_vaultUri, fullPath))).ConfigureAwait(false);
        }
示例#23
0
        private async Task MigrationGuide()
        {
            #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_Create
            AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
            KeyVaultClient            client   = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback));
            #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_Create

            #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                //@@AzureServiceTokenProvider provider = new AzureServiceTokenProvider();
                /*@@*/ provider = new AzureServiceTokenProvider();
                //@@KeyVaultClient client = new KeyVaultClient(
                /*@@*/ client = new KeyVaultClient(
                    new KeyVaultClient.AuthenticationCallback(provider.KeyVaultTokenCallback),
                    httpClient);
            }
            #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_CreateWithOptions

            {
                #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_SetSecret
                SecretBundle secret = await client.SetSecretAsync("https://myvault.vault.azure.net", "secret-name", "secret-value");

                #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_SetSecret
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_GetSecret
                // Get the latest secret value.
                SecretBundle secret = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", null);

                // Get a specific secret value.
                SecretBundle secretVersion = await client.GetSecretAsync("https://myvault.vault.azure.net", "secret-name", "e43af03a7cbc47d4a4e9f11540186048");

                #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_GetSecret
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_ListSecrets
                IPage <SecretItem> page = await client.GetSecretsAsync("https://myvault.vault.azure.net");

                foreach (SecretItem item in page)
                {
                    SecretIdentifier secretId = item.Identifier;
                    SecretBundle     secret   = await client.GetSecretAsync(secretId.Vault, secretId.Name);
                }

                while (page.NextPageLink != null)
                {
                    page = await client.GetSecretsNextAsync(page.NextPageLink);

                    foreach (SecretItem item in page)
                    {
                        SecretIdentifier secretId = item.Identifier;
                        SecretBundle     secret   = await client.GetSecretAsync(secretId.Vault, secretId.Name);
                    }
                }
                #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_ListSecrets
            }

            {
                #region Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_DeleteSecret
                // Delete the secret.
                DeletedSecretBundle deletedSecret = await client.DeleteSecretAsync("https://myvault.vault.azure.net", "secret-name");

                // Purge or recover the deleted secret if soft delete is enabled.
                if (deletedSecret.RecoveryId != null)
                {
                    DeletedSecretIdentifier deletedSecretId = deletedSecret.RecoveryIdentifier;

                    // Deleting a secret does not happen immediately. Wait a while and check if the deleted secret exists.
                    while (true)
                    {
                        try
                        {
                            await client.GetDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);

                            // Finally deleted.
                            break;
                        }
                        catch (KeyVaultErrorException ex) when(ex.Response.StatusCode == HttpStatusCode.NotFound)
                        {
                            // Not yet deleted...
                        }
                    }

                    // Purge the deleted secret.
                    await client.PurgeDeletedSecretAsync(deletedSecretId.Vault, deletedSecretId.Name);

                    // You can also recover the deleted secret using RecoverDeletedSecretAsync.
                }
                #endregion Snippet:Microsoft_Azure_KeyVault_Snippets_MigrationGuide_DeleteSecret
            }
        }
        public async Task DeleteAsync(IEnumerable <string> ids, CancellationToken cancellationToken)
        {
            GenericValidation.CheckBlobId(ids);

            await Task.WhenAll(ids.Select(id => _vaultClient.DeleteSecretAsync(_vaultUri, id)));
        }
示例#25
0
        public SecretBundle Delete(string key)
        {
            Task <DeletedSecretBundle> tdsb = keyVault.DeleteSecretAsync(this.baseSecretUri, key);

            return(tdsb.Result);
        }