Created
June 20, 2020 14:18
-
-
Save manoj-choudhari-git/4bcb27e64a95283c9e1bfbb8dab21c76 to your computer and use it in GitHub Desktop.
Program.cs for a .NET Core web application which uses service principal to connect to Azure Key Vault
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
CreateHostBuilder(args).Build().Run(); | |
} | |
public static IHostBuilder CreateHostBuilder(string[] args) => | |
Host.CreateDefaultBuilder(args) | |
.ConfigureAppConfiguration((context, config) => | |
{ | |
var keyVaultEndpoint = GetKeyVaultEndpoint(); | |
if (!string.IsNullOrEmpty(keyVaultEndpoint)) | |
{ | |
// In below connection string, replace | |
// {ClientId} with actual GUID representing client id | |
// {TenantId} with tenant id of Azure AD\ | |
// {ClientSecret} with the client secret you generated | |
var connectionString = "RunAs=App;AppId={ClientId};TenantId={TenantId};AppKey={ClientSecret}"; | |
var azureServiceTokenProvider = new AzureServiceTokenProvider(connectionString); | |
var keyVaultClient = new KeyVaultClient( | |
new KeyVaultClient.AuthenticationCallback( | |
azureServiceTokenProvider.KeyVaultTokenCallback)); | |
config.AddAzureKeyVault(keyVaultEndpoint, keyVaultClient, new DefaultKeyVaultSecretManager()); | |
} | |
}) | |
.ConfigureWebHostDefaults(webBuilder => | |
{ | |
webBuilder.UseStartup<Startup>(); | |
}); | |
private static string GetKeyVaultEndpoint() => "https://<<your-key-vault>>.vault.azure.net"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment