Created
June 20, 2020 15:52
-
-
Save manoj-choudhari-git/08e6d13d726765f3c8004308eec1a4cb to your computer and use it in GitHub Desktop.
Service Principal and Certificate with 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 | |
// {Thumbprint} with the subject of certificate | |
// StoreLocation is CurrentUser for our demo | |
var thumbprintConnString = "RunAs=App;AppId={ClientId};TenantId={TenantId};CertificateThumbprint={Thumbprint};CertificateStoreLocation={LocalMachine or CurrentUser};"; | |
// In below connection string, replace | |
// {ClientId} with actual GUID representing client id | |
// {TenantId} with tenant id of Azure AD | |
// {Subject} with the subject of certificate | |
// StoreLocation is CurrentUser for our demo | |
var subjectConnString = "RunAs=App;AppId={ClientId};TenantId={TenantId};CertificateSubjectName={Subject};CertificateStoreLocation={LocalMachine or CurrentUser}"; | |
var azureServiceTokenProvider = new AzureServiceTokenProvider(thumbprintConnString); | |
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