Keyvault

Why use a KeyVault?

To keep creds out of source control. (even if it’s just creds for dev/test)

Even if you don’t use keyvault, you should use environment variables to keep your secrets into being checked into git. The Keyvault API uses different mechanisms to access the keyvault - i.e. no code changes required if running locally or running in production.

The code

Here’s how to do it quickly in a Console application (works the same way when you do it for a web application - sample web app project available in ‘Further Reading’ section):

using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
static void Main(string[] args)
{
    string secretstr,error ;
    var azureServiceTokenProvider = new AzureServiceTokenProvider();  
    //details: by default, it uses VS creds, Azure CLI, then Azure AD (if running on a domain joined machine) - whatever works first - I ran into an issue where I wanted to run it under a different cred than VS and it took me a while to figure out how to get it to just use Azure CLI creds.  If you have different creds that you use in Visual Studio, pass in this parameter :"RunAs=Developer; DeveloperTool=AzureCli"

    try
    {
        var callback = new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback);  //this is where the magic happens (it tries multiple ways to authentication)
        var keyVaultClient = new KeyVaultClient(callback);

        var secrets = keyVaultClient.GetSecretsAsync("https://testvault123.vault.azure.net/").Result;   //get all secrets
        var secret = keyVaultClient.GetSecretAsync("https://testvault123.vault.azure.net/secrets/ambroseSecret").Result;  //get secret called 'ambroseSecret'

        secretstr = $"Secret: {secret.Value}";

    }
    catch (Exception exp)
    {
        error = $"Something went wrong: {exp.Message}";
    }

    var principal = azureServiceTokenProvider.PrincipalUsed != null ? $"Principal Used: {azureServiceTokenProvider.PrincipalUsed}" : string.Empty;

} //set a breakpoint here to inspect the variables

How does it work?

It works by using your local creds when in development and using a “managed identity”. When you run your code on an Azure App Service or an Azure VM with a managed identity enabled, the library automatically uses the managed identity. You might have to go to the Azure portal to enable managed identity.

Here’s how you enable managed identity on from the Azure portal - (as of 2019):

Further Reading

The official documentation:

https://docs.microsoft.com/en-us/azure/key-vault/service-to-service-authentication

Try it out with a sample web application:

https://github.com/Azure-Samples/app-service-msi-keyvault-dotnet

get yourself on the email list

//Powered by MailChimp - low volume, no spam

comments powered by Disqus