Skip to content

Instantly share code, notes, and snippets.


sergey-tihon/VaultSecretProvider.cs Secret

Last active Oct 8, 2019
What would you like to do?
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);
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();
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