Prerequisites
- A KeyVault in Azure with a Secret named "AzureServiceBusConnectionString" with the Azure Service Bus connection string.
- An environment variable named
KeyVaultUriwith 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.
Endpoint1sends aMessage1message toEndpoint2.Endpoint2replies toEndpoint1with aMessage2instance.
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
As a general practice security credentials should not be stored in environment variables, .env files, or hardcode in the source code. One option to achieve this is to rely on the DefaultAzureCredential which will try to access security information based on the runtime environment e.g. via Azure CLI locally, or via environment variables when running on Azure.
If running this sample on a machine in Azure (e.g., Virtual Machine, Azure Function, etc.) and authenticating with a Service Principal:
- Assign KeyVault permissions to the Service Principal (SPN) of the host.
DefaultAzureCredentialwill use eitherEnvironmentCredentialorManagedIdentityCredentialto authenticate automatically.
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 clicommand. - If you have access to multiple tenants, you may need to specify the correct one explicitly:
az login --tenant.<TENANT_ID> DefaultAzureCredentialwill useAzureCliCredentialto authenticate.
Otherwise, configure your environment accordingly, or provide a properly configured TokenCredential:
- See the supported mechanisms in the documentation.