Eric
Eric

Reputation: 1212

How to get the secret's value from Key Vault in Configuration Builder

I've followed some of the docs out there. So, setup the config builder, I added this code:

AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
builder.AddAzureKeyVault($"https://{Configuration.GetSection("Azure")["KeyVaultName"]}.vault.azure.net/", keyVaultClient, new DefaultKeyVaultSecretManager());

Now, I am trying to get the value from the named secret that is stored in the vault.

I thought I'd be able pull it out something like this:

builder.getSecret('DevDbPassword');

So that I can use to update the password using the SqlConnectionStringBuilder.

Can somebody help with figuring out how to get the secret?

Thanks Eric

Upvotes: 1

Views: 4368

Answers (2)

Tony Ju
Tony Ju

Reputation: 15609

Why did you want to get the secret in Configuration Builder? You can get secret this way:

     AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
     KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
     var secret = await keyVaultClient.GetSecretAsync("https://<YourKeyVaultName>.vault.azure.net/secrets/AppSecret")
             .ConfigureAwait(false);
     Message = secret.Value;

Refer to this document for more details.

If you still want to get the secret in Configuration Builder, you can refer to this sample.

public string Message { get; set; }

public AboutModel(IConfiguration configuration)
{
    _configuration = configuration;
}

private readonly IConfiguration _configuration = null;

public void OnGet()
{
    Message = "My key val = " + _configuration["AppSecret"];
}

Upvotes: 1

nlawalker
nlawalker

Reputation: 6514

This walks through it start to finish (make sure you're looking at the C# version).

Once you have things set up like you have them, your vault's secrets become part of the app's configuration. You need to inject an IConfiguration wherever you need a secret and get its value from that.

Upvotes: 0

Related Questions