Replacement for adding certificate in .net6 app

huangapple go评论65阅读模式
英文:

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&lt;IMyClient, MyClient&gt;(&quot;MPC&quot;, c =&gt;
            {
                c.DefaultRequestHeaders.ExpectContinue = true;
                c.BaseAddress = new Uri(configuration.GetConnectionString(&quot;Url&quot;));
            }).ConfigurePrimaryHttpMessageHandler(() =&gt;
                new HttpClientHandler().AddClientCertificate(configuration.GetValue&lt;string&gt;(&quot;MyCertificates:MyThumbprint&quot;)));
        }
    }

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($&quot;Certificate was not found for thumbprint {thumbPrint}&quot;);
            }
            return col[0];
        }
        finally
        {
            store.Close();
        }
    }
//appsettings

&quot;MyCertificates&quot;: {
    &quot;MyThumbprint&quot;: &quot;thumprintvalue&quot;
  },

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.IdentityAzure.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;
    }
}

输出:

Replacement for adding certificate in .net6 app

Replacement for adding certificate in .net6 app

验证 Key Vault Certificate 中的值:

Replacement for adding certificate in .net6 app

英文:

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:

 &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Azure.Identity&quot; Version=&quot;1.9.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Azure.Security.KeyVault.Secrets&quot; Version=&quot;4.5.0&quot; /&gt;
 &lt;/ItemGroup&gt;
  • 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 = &quot;https://harshukv4july.vault.azure.net/&quot;;

        var client = new SecretClient(new Uri(KVURI), KVCred);

        var CertName = &quot;Certificare4July&quot;;
        var secret = client.GetSecret(CertName);

        byte[] ThumbPrintinBytes = Convert.FromBase64String(secret.Value.Value);

        var KVCertificate = new X509Certificate2(ThumbPrintinBytes);
        var CertThumbPrint = KVCertificate.Thumbprint;
        Console.WriteLine($&quot;Thumbprint from Azure Certificate  : { CertThumbPrint }&quot;);

        return CertThumbPrint;
    }
}

OutPut:

Replacement for adding certificate in .net6 app

Replacement for adding certificate in .net6 app

Verify the value in Key Vault Certificate:

Replacement for adding certificate in .net6 app

huangapple
  • 本文由 发表于 2023年6月26日 19:01:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定