-
-
Save bachoang/8e986c31c71da41d696ac4d4b175df2a to your computer and use it in GitHub Desktop.
C Sharp code to access Azure Key Vault secret
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
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