Skip to content

Instantly share code, notes, and snippets.

@bachoang

bachoang/Program.cs Secret

Last active Jan 3, 2019
Embed
What would you like to do?
C Sharp code to access Azure Key Vault secret
using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static KeyVaultClient keyVaultClient;
static void Main(string[] args)
{
var clientId = "Your App ID";
var cerificateThumbprint = "Your Cert Thumbprint";
keyVaultClient = new KeyVaultClient(async (authority, resource, scope) =>
{
var authenticationContext = new AuthenticationContext(authority, null);
X509Certificate2 certificate;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificateCollection = store.Certificates.Find(X509FindType.FindByThumbprint, cerificateThumbprint, false);
if (certificateCollection == null || certificateCollection.Count == 0)
{
throw new Exception("Certificate not installed in the store");
}
certificate = certificateCollection[0];
}
finally
{
store.Close();
}
var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);
var result = await authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate);
var token = result.AccessToken;
return token;
});
var secret = keyVaultClient.GetSecretAsync("https://blogkv123.vault.azure.net/secrets/SQLPassword/");
Console.Write(secret.Result.Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment