如何更改 ASP.NET 核心中本地开发的默认 SSL 证书?

How can I change the default SSL certificate for local development in ASP.NET core?

当 Linux 上 ASP.NET 本地 ASP.NET 核心应用程序时,如何将我自己的证书配置为 Kestrel 使用的“默认”证书?

我知道我可以 运行 dotnet dev-certs https 命令来生成新的开发证书,但这会生成新的自签名证书。我不想必须信任这个证书 - 我已经有自己的本地 CA 用于开发,并且想签署一个证书供 ASP.NET 核心使用。

我也知道您可以配置 Kestrel 在我的应用程序代码中使用的证书 (https://devblogs.microsoft.com/aspnet/configuring-https-in-asp-net-core-across-different-platforms/),但我认为这不应该是应用程序的一部分。我个人更喜欢在本地使用我自己的 CA 签名证书,如果其他开发人员乐于信任自动生成的证书,我不想强​​迫他们管理他们自己的证书。

我尝试将证书放入创建自签名开发证书的本地“我的”证书存储区 (~/.dotnet/corefx/cryptography/x509stores/my/),但它没有被使用 - 我收到了发生的错误当您根本没有证书时:

crit: Microsoft.AspNetCore.Server.Kestrel[0] Unable to start Kestrel. System.InvalidOperationException: Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date.

是否可以配置我自己的证书,还是我必须使用 dotnet core 生成的证书?

简答:

事实证明 ASP.NET 核心在配置 Kestrel 时使用的默认证书上查找特定扩展。如果要提取证书,需要设置扩展名“1.3.6.1.4.1.311.84.1.1”,并且该扩展名的原始字节值应>= 2 (from reading the source code).

将具有此扩展名(和一些其他基本扩展名)的证书放入“我的”存储中允许默认使用该证书。

长答案:

(先阅读简答)

您不能使用现有的证书。因为 ASP.NET 核心需要对其使用的证书进行特定扩展,所以您需要创建一个新证书才能使用。但是,只要您正确生成请求,您仍然可以使用由 CA 签名的证书。

假设使用 openssl,您可以在生成证书请求时通过配置文件来促进这一点:

asp_config.conf

[ req ]
default_bits = 2048
distinguished_name = dn
req_extensions = aspnet

[ dn ]
CN = localhost

[ aspnet ]
basicConstraints = critical, CA:FALSE
keyUsage = critical, digitalSignature, keyEncipherment
extendedKeyUsage = critical, serverAuth
subjectAltName = critical, DNS:localhost
1.3.6.1.4.1.311.84.1.1 = DER:02

然后您可以 运行 openssl 命令使用此配置生成签名请求:

openssl req -new -config asp_config.conf -keyout local_asp_dev.key -out local_asp_dev.csr -nodes

生成请求后,用您的 CA 签名。

openssl x509 -req -in local_asp_dev.csr -CA /path/to/CA.pem -CAkey /path/to/CA.key -CAcreateserial -out local_asp_dev.crt -days 365 -sha256 -extensions aspnet -extfile asp_config.conf

You need to specify the extensions to grant to the certificate using the -extensions option. This options looks at the specified configuration section in the referenced file.

签名后,您需要将证书打包到 pfx 文件中:

openssl pkcs12 -in local_asp_dev.crt -inkey local_asp_dev.key -export -out local_asp_dev.pfx

打包您的证书后,只需将其放入您的“我的”商店 - ASP.NET 将拾取它并使用它来为您的 HTTPS 端点提供服务。 (您可能需要删除在此商店中自动创建的任何其他开发证书)。

mv local_asp_dev.pfx ~/.dotnet/corefx/cryptography/x509stores/my/

请注意,此商店在 Linux 上的位置被视为内部实施细节,可能会发生变化。 ASP.NET 核心的未来版本也完全有可能需要不同的扩展值。

此解决方案是针对 ASP.NET Core 3.1

开发和测试的

其他参考资料: