-
-
Save sergey-tihon/e367a333320760a97a64a596ad225e6e 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
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using System.Security.Cryptography.X509Certificates; | |
using VaultSharp; | |
using VaultSharp.V1.AuthMethods.Cert; | |
namespace SergeyTihon.App.Configuration | |
{ | |
public class VaultSecretProvider | |
{ | |
public VaultSecretProvider(string vaultUrl, string vaultNamespace, string certificateThumbprint) | |
{ | |
var clientCertificate = GetCertificate(certificateThumbprint); | |
var authMethod = new CertAuthMethodInfo(clientCertificate); | |
_vaultClient = new VaultClient(new VaultClientSettings(vaultUrl, authMethod) | |
{ | |
BeforeApiRequestAction = (httpClient, httpRequestMessage) => | |
{ | |
httpRequestMessage.Headers.Add("X-Vault-Namespace", vaultNamespace); | |
} | |
}); | |
} | |
public static X509Certificate2 GetCertificate(string certThumbprint) | |
{ | |
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); | |
store.Open(OpenFlags.ReadOnly); | |
var certCollection = store.Certificates; | |
// Find unexpired certificates. | |
var currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); | |
// From the collection of unexpired certificates, find the ones with the correct thumbprint. | |
var signingCert = currentCerts.Find(X509FindType.FindByThumbprint, certThumbprint, false); | |
// Return the first certificate in the collection, has the right name and is current. | |
var cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault(); | |
store.Close(); | |
if (cert is null) | |
{ | |
throw new DataException($"Cannot find valid certificate with thumbprint {certThumbprint}"); | |
} | |
return cert; | |
} | |
private readonly VaultClient _vaultClient; | |
public async Task<Dictionary<string, object>> GetValue(string path, string mountPoint) | |
{ | |
var secret = await _vaultClient.V1.Secrets.KeyValue.V1.ReadSecretAsync(path, mountPoint); | |
return secret.Data; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment