A hypothetical web-site currently connects using:
public SqlConnection CreateConnection()
{
DbConnection connection = new SqlConnection();
connection.Conne
There's now a low-ceremony way to call Key Vault from App Service with zero custom code via Key Vault references. https://docs.microsoft.com/en-us/azure/app-service/app-service-key-vault-references
App Setting example that populates value from Key Vault:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/ec96f02080254f109c51a1f14cdb1931)
If you don't want the version identifier:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/mysecret/)
You need to setup Managed Identity first between your App Service instance and Key Vault to be able to use Key Vault references.
I have nothing against Key Vault (i think it's a great product!), however i can't help myself but think you are overengineering this.
I would simply use the built-in Application Settings functionality in Azure App Service:
Connection strings
For .NET apps, these connection strings are injected into your .NET configuration connectionStrings settings at runtime, overriding existing entries where the key equals the linked database name.
Web App → Application Settings → Connection Strings → Add a Connection String and name it db
.
String GetConnectionString()
{
// Get the Connection String from Application Settings (App Service)
// with graceful fallback to web.config
string cs = WebConfigurationManager.ConnectionStrings["db"].ConnectionString;
if (cs == null)
throw new Exception("Could not locate DB connection string");
return cs;
}
What's the difference between the WebConfigurationManager and the ConfigurationManager?
Since Managed Service Identity became a thing, acquiring an access token no longer demands secrets (service principal credentials) being stored in your service to access Key Vault, which is a much better proposition. Here's a Node.js sample just to spice up this answer a little bit:
// Get an access token from Managed Service Identity
// on an Azure IaaS VM
async function getAccessTokenWithMSI() {
let msi = await axios.get('http://169.254.169.254/metadata/identity/oauth2/token',
{
params: {
'api-version': '2018-02-01',
'resource': 'https://vault.azure.net'
},
headers: {
'Metadata': 'true'
},
timeout: 2000
});
return msi.data.access_token;
}
and then:
// Get a secret from Key Vault
async function getSecret(accessToken, secretUrl) {
let response;
try {
response = await axios.get(secretUrl,
{
params: { 'api-version': '2016-10-01' },
headers: { 'Authorization': `Bearer ${accessToken}` },
timeout: 3000
});
}
catch (e) {
console.log('\nError calling Key Vault:,
e.response.status, e.response.statusText, e.response.data);
}
console.log('\nGet Secret response from Key Vault: ',
JSON.stringify(response.data, null, 4));
return response.data;
}