前言
之前有介绍过读写 Certificate Store, 但在 production server 经常会遇到权限的问题.
为了一劳永逸, 可以考虑把 Certificate 放到 Azure Key Vault 里, 然后通过 API 去拿.
这样做的另一个好处是对 Server 依赖更少.
主要参考:
How can I create an X509Certificate2 object from an Azure Key Vault KeyBundle
Azure Key Vault Certificate client library for .NET
Azure Setup
去 Key Vault 页面点击 import
选择 import 添加名字密码就可以了.
ASP.NET Core Setup
install nuget
dotnet add package Azure.Identity dotnet add package Azure.Security.KeyVault.Certificates dotnet add package Azure.Security.KeyVault.Secrets
get certificate from Azure
var certificateClient = new CertificateClient(new Uri("https://kv-name.vault.azure.net/"), new DefaultAzureCredential()); var secretClient = new SecretClient(new Uri("https://kv-name.vault.azure.net/"), new DefaultAzureCredential()); var certResponse = await certificateClient.GetCertificateAsync("Certificate Name"); var identifier = new KeyVaultSecretIdentifier(certResponse.Value.SecretId); var secretResponse = await secretClient.GetSecretAsync(identifier.Name, identifier.Version); var secret = secretResponse.Value; var privateKeyBytes = Convert.FromBase64String(secret.Value); var certificate = new X509Certificate2(rawData: privateKeyBytes, password: (string?)null, keyStorageFlags: X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
list all certificate
AsyncPageable<CertificateProperties> allCertificates = client.GetPropertiesOfCertificatesAsync(); await foreach (CertificateProperties certificateProperties in allCertificates) { Console.WriteLine(certificateProperties.Name); }
注意它返回的是一个叫 AsyncPageable 的冬冬. 它不是很好操作.
要好的调用体验可以参考: Use System.Linq.Async with AsyncPageable
import certificate to Azure
TODO...