Yes, it is recommended to store sensitive data such as database connection strings, passwords, and keys in Azure Key Vault instead of hard-coding them in your application code or configuration files. Here are the high-level steps to accomplish this:
- Create an Azure Key Vault and grant your Azure web application permission to access it. You can do this in the Azure portal by creating an access policy and assigning it to your web application's service principal.
- Store the database password in Azure Key Vault as a secret. You can do this in the Azure portal or using Azure CLI or PowerShell.
- Modify your web application to read the database password from Azure Key Vault. You can use the Azure Key Vault client library for .NET to do this. Here is some sample code
var keyVaultClient = new KeyVaultClient(
new KeyVaultClient.AuthenticationCallback(
async (authority, resource, scope) =>
{
var authContext = new AuthenticationContext(authority);
var credential = new ClientCredential(clientId, clientSecret);
var result = await authContext.AcquireTokenAsync(resource, credential);
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token");
}
return result.AccessToken;
}));
var secretUri = $"https://{keyVaultName}.vault.azure.net/secrets/{secretName}/{secretVersion}";
var secret = await keyVaultClient.GetSecretAsync(secretUri);
var connectionString = string.Format(connectionStringTemplate, secret.Value);
In this code, keyVaultClient is an instance of the KeyVaultClient class from the Azure Key Vault client library. clientId and clientSecret are the client ID and client secret of the Azure AD application that has permission to access the Key Vault. secretName and secretVersion are the name and version of the secret that contains the database password.