如何使用商店证书为NET Core 2.1正确设置HTTPS

问题描述 投票:6回答:1

我使用在Stackoverflow上找到的建议使用Powershell生成了证书:

New-SelfSignedCertificate -Subject "CN=Test Code Signing" -Type CodeSigningCert -KeySpec "Signature" -KeyUsage "DigitalSignature" -FriendlyName "Test Code Signing" -NotAfter (get-date).AddYears(5)

enter image description here

我已将此证书复制并粘贴到受信任的根证书颁发机构。

我的NET Core WebAPI Program.cs设置如下:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options=> {
            options.Listen(IPAddress.Loopback, 5000);  // http:localhost:5000
            options.Listen(IPAddress.Any, 80);         // http:*:80
            options.Listen(IPAddress.Loopback, 443, listenOptions =>
            {
                //how to use a certificate store here? 
                //listenOptions.UseHttps("certificate.pfx", "password");
                //listenOptions.UseHttps(StoreName.My, "Test Code Signing", allowInvalid: true);
                listenOptions.UseHttps(StoreName.My, "localhost", allowInvalid: true);

            }); 
});

localhost测试代码签名均未在此代码中工作,因为找不到它们。也许我缺少了一些东西。试图遵循这份MSDN文档,但没有运气。

目前,Chrome浏览器中显示的证书与我在个人受信任的根证书颁发机构中拥有的证书不同:

enter image description here

如何设置Kestrel,以选择浏览器信任的自签名证书,并避免阻止诸如NET::ERR_CERT_AUTHORITY_INVALID之类的消息?

c# https ssl-certificate asp.net-core-webapi kestrel-http-server
1个回答
0
投票

您正在使用的UseHttps重载不允许您指定商店位置,因此默认为StoreLocation.CurrentUser。您需要调用一个方法,该方法从存储中检索证书并将其传递给UseHttps方法。 MSDN文章的底部提供了更多细节,但这是一个示例(您需要将“您的通用名称”替换为证书通用名称):

    static void Main(string[] args)
    {
        var host = new WebHostBuilder()
             .UseKestrel(options =>
            {
                options.Listen(IPAddress.Any, 443, listenOptions =>
                {
                    listenOptions.UseHttps(GetHttpsCertificateFromStore());
                    listenOptions.NoDelay = true;
                });

            })
            .Build();
    }

    private static X509Certificate2 GetHttpsCertificateFromStore()
    {
        using (var store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
        {
            store.Open(OpenFlags.ReadOnly);
            var certCollection = store.Certificates;
            var currentCerts = certCollection.Find(X509FindType.FindBySubjectDistinguishedName, "CN=[your common name here]", false);

            if (currentCerts.Count == 0)
            {
                throw new Exception("Https certificate is not found.");
            }

            return currentCerts[0];
        }
    }

https://docs.microsoft.com/bs-latn-ba/azure/service-fabric/service-fabric-tutorial-dotnet-app-enable-https-endpoint

© www.soinside.com 2019 - 2024. All rights reserved.