英文:
Replacement for adding certificate in .net6 app
问题
我正在努力替换从 .NET 4.8 升级到 .NET 6 时的现有添加证书代码。
以下是升级后的设置:
Program.cs
private static async Task Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
LoadConfiguration(builder);
var startup = new MyWebApp.Startup(builder.Configuration);
startup.ConfigureServices(builder.Services);
WebApplication app = builder.Build();
await app.RunAsync().ConfigureAwait(false);
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// 注册
RegisterServices(services);
// 注册
}
void RegisterServices(IServiceCollection services)
{
// DbContext
// 其他项目的注册
// Repo 等
services.RegisterClients(Configuration);
}
Client CS Project
//Extension
public static class DIExtension
{
// 向给定的构建器注册客户端
public static void RegisterClients(this IServiceCollection services, IConfiguration configuration)
{
//services.AddHttpClient
services.AddHttpClient<IMyClient, MyClient>("MPC", c =>
{
c.DefaultRequestHeaders.ExpectContinue = true;
c.BaseAddress = new Uri(configuration.GetConnectionString("Url"));
}).ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler().AddClientCertificate(configuration.GetValue<string>("MyCertificates:MyThumbprint")));
}
}
HttpHandlerExt
public static HttpClientHandler AddClientCertificate(this HttpClientHandler handler, string thumbPrint)
{
handler = handler ?? new HttpClientHandler();
var cert = GetMyCertificate(thumbPrint);
if (cert == null)
{
return handler;
}
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(cert);
return handler;
}
private static X509Certificate2 GetMyCertificate(string thumbPrint)
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);
if (col == null || col.Count == 0)
{
throw new CertificateException($"Certificate was not found for thumbprint {thumbPrint}");
}
return col[0];
}
finally
{
store.Close();
}
}
// appsettings
"MyCertificates": {
"MyThumbprint": "thumprintvalue"
},
指纹值在 KV 的证书中可用。我不希望指纹值直接出现在 appsettings 中。如果需要额外信息,请告诉我,我尽可能提供了尽可能多的信息和代码。
英文:
I am struggling with replacing my existing add certificate code when upgrading from .net 4.8 to .net 6
Here is the set up post upgrade:
Program.cs
private static async Task Main(string[] args)
{
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
LoadConfiguration(builder);
var startup = new MyWebApp.Startup(builder.Configuration);
startup.ConfigureServices(builder.Services);
WebApplication app = builder.Build();
await app.RunAsync().ConfigureAwait(false);
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//register
RegisterServices(services);
//register
}
void RegisterServices(IServiceCollection services)
{
// DbContext
// Other project registrations
//Repo etc
services.RegisterClients(Configuration);
}
Client CS Project
//Extension
public static class DIExtension
{
// Registers the clients to the given builder
public static void RegisterClients(this IServiceCollection services, IConfiguration configuration)
{
//services.AddHttpClient
services.AddHttpClient<IMyClient, MyClient>("MPC", c =>
{
c.DefaultRequestHeaders.ExpectContinue = true;
c.BaseAddress = new Uri(configuration.GetConnectionString("Url"));
}).ConfigurePrimaryHttpMessageHandler(() =>
new HttpClientHandler().AddClientCertificate(configuration.GetValue<string>("MyCertificates:MyThumbprint")));
}
}
HttpHandlerExt
public static HttpClientHandler AddClientCertificate(this HttpClientHandler handler, string thumbPrint)
{
handler = handler ?? new HttpClientHandler();
var cert = GetMyCertificate(thumbPrint);
if (cert == null)
{
return handler;
}
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(cert);
return handler;
}
private static X509Certificate2 GetMyCertificate(string thumbPrint)
{
var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
store.Open(OpenFlags.ReadOnly);
var col = store.Certificates.Find(X509FindType.FindByThumbprint, thumbPrint, false);
if (col == null || col.Count == 0)
{
throw new CertificateException($"Certificate was not found for thumbprint {thumbPrint}");
}
return col[0];
}
finally
{
store.Close();
}
}
//appsettings
"MyCertificates": {
"MyThumbprint": "thumprintvalue"
},
The thumprints are available in Certificates of KV. I do not want the thumprint value to be available directly in appsetting.
Please let me know if any additional information is required, I have tried to give as much information and code as possible from my end.
答案1
得分: 1
We can get the Thumbprint from the Azure Key Vault Certificate by using Azure Key Vault SDK.
- We just need to pass the Key Vault URI.
安装 Azure.Identity
和 Azure.Security.KeyVault.Secrets
NuGet 包
我的 .csproj
文件:
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.9.0" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
</ItemGroup>
- 首先,我们将以字节格式检索指纹,然后使用
X509Certificate2
进行转换
我的 Startup.cs
文件:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration;
using System.Security.Cryptography.X509Certificates;
internal class Startup
{
private ConfigurationManager configuration;
public Startup(ConfigurationManager configuration)
{
this.configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
RegisterServices(services);
}
void RegisterServices(IServiceCollection services)
{
string Thumbprint = GetCertificateThumbprint();
}
static string GetCertificateThumbprint()
{
var KVCred = new DefaultAzureCredential();
var KVURI = "https://harshukv4july.vault.azure.net/";
var client = new SecretClient(new Uri(KVURI), KVCred);
var CertName = "Certificare4July";
var secret = client.GetSecret(CertName);
byte[] ThumbPrintinBytes = Convert.FromBase64String(secret.Value.Value);
var KVCertificate = new X509Certificate2(ThumbPrintinBytes);
var CertThumbPrint = KVCertificate.Thumbprint;
Console.WriteLine($"Azure 证书的 Thumbprint : { CertThumbPrint }");
return CertThumbPrint;
}
}
输出:
验证 Key Vault Certificate
中的值:
英文:
We can get the Thumbprint from the Azure Key Vault Certificate by using Azure Key Vault SDK.
- We just need to pass the Key Vault URI.
Install the Azure.Identity
and Azure.Security.KeyVault.Secrets
NuGet Packages
My .csproj
file:
<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.9.0" />
<PackageReference Include="Azure.Security.KeyVault.Secrets" Version="4.5.0" />
</ItemGroup>
- First, we will retrieve the Thumbprint in the bytes format, later convert it using
X509Certificate2
My Startup.cs
file:
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using Microsoft.Extensions.Configuration;
using System.Security.Cryptography.X509Certificates;
internal class Startup
{
private ConfigurationManager configuration;
public Startup(ConfigurationManager configuration)
{
this.configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
RegisterServices(services);
}
void RegisterServices(IServiceCollection services)
{
string Thumbprint = GetCertificateThumbprint();
}
static string GetCertificateThumbprint()
{
var KVCred = new DefaultAzureCredential();
var KVURI = "https://harshukv4july.vault.azure.net/";
var client = new SecretClient(new Uri(KVURI), KVCred);
var CertName = "Certificare4July";
var secret = client.GetSecret(CertName);
byte[] ThumbPrintinBytes = Convert.FromBase64String(secret.Value.Value);
var KVCertificate = new X509Certificate2(ThumbPrintinBytes);
var CertThumbPrint = KVCertificate.Thumbprint;
Console.WriteLine($"Thumbprint from Azure Certificate : { CertThumbPrint }");
return CertThumbPrint;
}
}
OutPut:
Verify the value in Key Vault Certificate
:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论