Using secrets stored with Secret Manager in an application is accomplished by calling
AddUserSecrets on the
ConfigurationBuilder
instance to include secrets for the application in
its configuration. The generic parameter
T
should be a type from the assembly that the UserSecretId
was applied to. Usually, using
AddUserSecrets is fine.
The
AddUserSecrets()
is included in the default options for the Development environment
when using the
CreateDefaultBuilder
method in
Program.cs .
Use Azure Key Vault to protect secrets at production
time
Secrets stored as environment variables or stored by the Secret Manager tool are still stored locally
and unencrypted on the machine. A more secure option for storing secrets is
Azure Key Vault
, which
provides a secure, central location for storing keys and secrets.
The
Azure.Extensions.AspNetCore.Configuration.Secrets package allows an ASP.NET Core
application to read configuration information from Azure Key Vault. To start using secrets from an
Azure Key Vault, you follow these steps:
1.
Register your application as an Azure AD application. (Access to key vaults is managed by Azure
AD.) This can be done through the Azure management portal.
Alternatively, if you want your application to authenticate using a certificate instead of a
password or client secret, you can use the
New-AzADApplication
PowerShell cmdlet. The
certificate that you register with Azure Key Vault needs only your public key. Your application will
use the private key.
2.
Give the registered application access to the key vault by creating a new service principal. You
can do this using the following PowerShell commands:
$sp
= New-AzADServicePrincipal -ApplicationId
""
Set-AzKeyVaultAccessPolicy -VaultName
""
-ServicePrincipalName
$sp
.
ServicePrincipalNames
[0] -PermissionsToSecrets all -ResourceGroupName
"Resource Group>"
3.
Include the key vault as a configuration source in your application by calling the
AzureKeyVaultConfigurationExtensions.AddAzureKeyVault extension method when you create an
IConfigurationRoot
instance.
Note that calling
AddAzureKeyVault
requires the application ID that was registered and given access
to the key vault in the previous steps. Or you can firstly running the Azure CLI command:
az login
,
then using an overload of
AddAzureKeyVault
that takes a DefaultAzureCredential in place of the
client.
334
CHAPTER 8 | Make secure .NET Microservices and Web Applications
Important We recommend that you register Azure Key Vault as the last configuration provider, so it can override
configuration values from previous providers.