Skip to content

Instantly share code, notes, and snippets.


bachoang/Program.cs Secret

Last active Jan 3, 2019
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);
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];
var clientAssertionCertificate = new ClientAssertionCertificate(clientId, certificate);
var result = await authenticationContext.AcquireTokenAsync(resource, clientAssertionCertificate);
var token = result.AccessToken;
return token;
var secret = keyVaultClient.GetSecretAsync("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment