代码之家  ›  专栏  ›  技术社区  ›  Junior Mayhé

如何使用存储证书为netcore2.1正确设置HTTPS

  •  6
  • Junior Mayhé  · 技术社区  · 8 年前

    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

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

    我的网络核心WebAPI程序.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);
    
                }); 
    });
    

    都不是 或 测试代码签名 MSDN 没有运气的文档。

    现在googlechrome上显示的证书与我在的不同 个人的 和 受信任的根证书颁发机构 :

    enter image description here

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

    0 回复  |  直到 8 年前
        1
  •  1
  •   alex    6 年前

    这种方法对我有效:

    private static X509Certificate2 LoadCertificate(string p_storeName, string p_storeLocation, string p_Host, string p_FilePath, string p_Password, IHostingEnvironment environment)
    {
      if (p_storeName != "" && p_storeLocation != "")
      {
          using (var store = new X509Store(p_storeName, Enum.Parse<StoreLocation>(p_storeLocation)))
           {
               store.Open(OpenFlags.ReadOnly);
    
                bool validOnly = false;
                if (environment.IsDevelopment() == true) { validOnly = false; }
                else
                {
                    if (p_Host == "localhost") { validOnly = false; }
                    else { validOnly = true; }
                }
    
                var certificate = store.Certificates.Find(
                X509FindType.FindBySubjectName,p_Host,validOnly: validOnly);
    
                if (certificate.Count == 0)
                {
                    throw new InvalidOperationException($"Certificate not found for {p_Host}.");
                }
                     return certificate[0];
                }
           }
    
           if (p_FilePath != "" && p_Password != "")
           {
              return new X509Certificate2(p_FilePath, p_Password);
           }
           throw new InvalidOperationException("No valid certificate configuration found for the current endpoint.");
        }
    
        2
  •  0
  •   Ian Gibson    7 年前

    您使用的UseHttps重载不允许您指定存储位置,因此它默认为存储位置.CurrentUser. 您需要调用一个从存储中检索证书并将其传递给UseHttps方法的方法。下面有一篇MSDN文章提供了更详细的信息,我在下面提供了一个示例(您需要将“您的common name here”替换为“certificate common name”):

        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