Skip to content

Instantly share code, notes, and snippets.

@bachoang
Last active January 3, 2019 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bachoang/8e986c31c71da41d696ac4d4b175df2a to your computer and use it in GitHub Desktop.
Save bachoang/8e986c31c71da41d696ac4d4b175df2a to your computer and use it in GitHub Desktop.
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