Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Modernization
Samples

Azure Service Bus KeyVault Sample

Prerequisites

  • A KeyVault in Azure with a Secret named "AzureServiceBusConnectionString" with the Azure Service Bus connection string.
  • An environment variable named KeyVaultUri with the URI of the KeyVault.
  • Access permissions setup for the endpoints to be able to read the secret.

Code walk-through

This sample shows a basic two-endpoint scenario exchanging messages with each other so that:

  • Endpoints extract the connection string from Azure KeyVault.
  • Endpoint1 sends a Message1 message to Endpoint2.
  • Endpoint2 replies to Endpoint1 with a Message2 instance.

KeyVault client

public async Task<string> GetConfiguration(string key)
{
    // We take the provided TokenCredential or use the default one
    // The default one uses many mechanisms to authenticate, e.g., environment variables, VisualStudio, Azure CLI, Azure PowerShell
    TokenCredential actualTokenCredential = TokenCredential ?? new DefaultAzureCredential();
    SecretClient client = new SecretClient(new Uri(KeyVaultUri), actualTokenCredential);

    // We use the client to download the setting
    Response<KeyVaultSecret> secretResponse = await client.GetSecretAsync(key);

    // We can now extract the setting value
    var secret = secretResponse.Value;

    return secret.Value;
}

Running the sample

If running this sample on a machine in Azure (e.g., Virtual Machine, Azure Function, etc.) and authenticating with a Service Principal:

If running this sample on a developer computer and authenticating with your domain account:

  • Install Azure CLI as in the documentation.
  • Grant proper permissions to the account you use to authenticate against Azure.
  • Authenticate in the Azure CLI using az cli command.
  • If you have access to multiple tenants, you may need to specify the correct one explicitly: az login --tenant <TENANT_ID>.
  • DefaultAzureCredential will use AzureCliCredential to authenticate.

Otherwise, configure your environment accordingly, or provide a properly configured TokenCredential:

Related Articles