ASP.NET Core (3.1) 在自托管 (Kestrel) 应用程序中重新使用 IIS 证书

Dal*_*pić 0 ssl ssl-certificate kestrel-http-server asp.net-core .net-core-3.1

我有一个 ASP.NET Core (3.1) 应用程序,它是自托管的并作为服务运行。我想为其公开一个 HTTPS 端点。在同一台计算机上安装了一个 IIS,其中已配置了 https 和证书: 在此输入图像描述

该证书似乎存储在本地计算机证书存储中: 证书管理器

我还可以通过 powershell 列出它:

> get-childitem cert:\LocalMachine\My\ | format-table NotAfter, Subject

NotAfter            Subject
--------            -------
27.10.2023 07:38:45 <irrelevant>
08.03.2022 09:52:44 CN=a7642e58-2cdf-4e9b-a277-60fad84d7c64, DC=3336d6b0-b132-47ee-a49b-3ab470a5336e
23.02.2022 21:51:53 CN=a7642e58-2cdf-4e9b-a277-60fad84d7c64, DC=3336d6b0-b132-47ee-a49b-3ab470a5336e
27.10.2031 06:48:06 CN=a7642e58-2cdf-4e9b-a277-60fad84d7c64
26.10.2024 10:41:03 E=****.com, CN=****, OU=IT, O=****, L=****, S=***, C=**
Run Code Online (Sandbox Code Playgroud)

我更改了 appsettings.json 以使用商店中的证书:

{
  "Logging": {
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://*:5000"
      },
      "HttpsDefaultCert": {
        "Url": "https://*:5001"
      }
    },
    "Certificates": {
      "Default": {
        "Subject": "E=****.com, CN=****, OU=IT, O=****, L=****, S=***, C=**",
        "Store": "My",
        "Location": "LocalMachine",
        "AllowInvalid": "true"
      }
    }
  }
}

Run Code Online (Sandbox Code Playgroud)

然而这似乎不起作用。我总是收到以下错误:

 System.InvalidOperationException: The requested certificate E=****.com, CN=****, OU=IT, O=****, L=****, S=***, C=** could not be found in LocalMachine/My with AllowInvalid setting: True
Run Code Online (Sandbox Code Playgroud)

我不知道可能是什么问题。我认为唯一可能有问题的是证书主题实际上包含主题中的换行符:
证书

我不知道这是否是问题所在,并且我不知道如何在 appsettings.json 中输入它,因为无法输入多行值。

Dal*_*pić 8

我已经设法找到了这个问题。Kestrel在搜索证书时使用FindBySubjectName 。

FindBySubjectName 执行子字符串搜索,并且不会匹配证书的完整主题。如果您的证书主题是类似的内容,'CN=my-certificate'那么搜索'CN=my-certificate'将找不到任何内容。仅搜索即可'my-certificate'

附加说明:除了指定正确的搜索表达式之外,请确保运行应用程序的帐户具有足够的权限来从证书存储中读取证书。证书确实具有 ACL,因此您不必以管理员身份运行应用程序。