Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Created June 20, 2020 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manoj-choudhari-git/4bcb27e64a95283c9e1bfbb8dab21c76 to your computer and use it in GitHub Desktop.
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
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