Last active
November 17, 2016 00:49
-
-
Save sjwaight/8aafc2b94be58ba4bc93fa8e69bfadca to your computer and use it in GitHub Desktop.
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
#r "System.Runtime" | |
#r "System.Threading.Tasks" | |
using System; | |
using System.Threading.Tasks; | |
using System.Web.Configuration; | |
using Microsoft.IdentityModel.Clients.ActiveDirectory; | |
using Microsoft.Azure.KeyVault; | |
using System.Security.Cryptography.X509Certificates; | |
public static string GetKeyVaultSecret(string secretNode) | |
{ | |
var secretUri = string.Format("{0}{1}", "https://mytestvault.vault.azure.net/secrets/", secretNode); | |
var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken)); | |
return keyVaultClient.GetSecretAsync(secretUri).Result.Value; | |
} | |
private static async Task<string> GetAccessToken(string authority, string resource, string scope) | |
{ | |
var authContext = new AuthenticationContext(authority); | |
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, GetCert()); | |
if (result == null) | |
throw new InvalidOperationException("Failed to obtain the JWT token"); | |
return result.AccessToken; | |
} | |
private static ClientAssertionCertificate GetCert() | |
{ | |
// could read following values from App Settings if you wanted to | |
var clientAssertionCertPfx = FindCertificateByThumbprint("C6XXXXXX53E8DXXXX2B217F6CD0A4A0F9E5390A5"); | |
// the left-hand GUID here is the output of $adapp.ApplicationId in our Service Principal setup script | |
return new ClientAssertionCertificate("XXXXXXXX-XXXX-XXXX-XXXX-e643a85c7c19", clientAssertionCertPfx); | |
} | |
private static X509Certificate2 FindCertificateByThumbprint(string findValue) | |
{ | |
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); | |
try | |
{ | |
store.Open(OpenFlags.ReadOnly); | |
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindByThumbprint, findValue, false); | |
if (col == null || col.Count == 0) | |
{ | |
return null; | |
} | |
return col[0]; | |
} | |
finally | |
{ | |
store.Close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment