cowinr
8/10/2019 - 4:09 PM

Key Vault

# Create key vault
az group create --name "keyvault" --location northeurope
az keyvault create --name "ric01-test-keyvault" --resource-group "keyvault" --enable-soft-delete true --location northeurope

# Add a secret
az keyvault secret set --vault-name "ric01-test-keyvault" --name "AppSecret" --value "MySecret"
az keyvault secret show --name "AppSecret" --vault-name "ric01-test-keyvault"

# Assign identity to webapp
az webapp identity assign --name "myapp" --resource-group "keyvault"

# {                                                       
#   "identityIds": null,                                  
#   "principalId": "0bddedc9-xxxx-xxxx-xxxx-77c891a16a18",
#   "tenantId": "f447e5ca-xxxx-xxxx-xxxx-370ff157fdb6",   
#   "type": "SystemAssigned"                              
# }                                                       

# Allow webapp identity to access key vault
az keyvault set-policy --name "ric01-test-keyvault" --object-id "0bddedc9-xxxx-xxxx-xxxx-77c891a16a18" --secret-permissions get list
string clientId = "...";
string clientSecret = "...";
string tenantId = "...";
string subscriptionId = "...";

AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(clientId, clientSecret, tenantId, AzureEnvironment.AzureGlobalCloud).WithDefaultSubscription(subscriptionId);

\!h KeyVaultClient kvClient = new KeyVaultClient(async (authority, resource, scope) =>
{
    var adCredential = new ClientCredential(clientId, clientSecret);
    var authenticationContext = new AuthenticationContext(authority, null);
    return (await authenticationContext.AcquireTokenAsync(resource, adCredential)).AccessToken;
});

// Save a secret
// url == https://<your-unique-keyvault-name>.vault.azure.net/secrets/
\!h await kvClient.SetSecretAsync($"{kvURL}", secretName, secretValue);

// Retrieve a secret
\!h var keyvaultSecret = await kvClient.GetSecretAsync($"{kvURL}", secretName).ConfigureAwait(false);