简体   繁体   English

如何使用自托管ASP.NET Core 2应用程序(httpsys)进行HTTPS(SSL)

[英]How to HTTPS (SSL) with self-hosted ASP.NET Core 2 app (httpsys)

I wrote a little ASP.NET Core 2 application. 我写了一个小的ASP.NET Core 2应用程序。 It runs as a service, so no IIS. 它作为服务运行,因此没有IIS。 It runs on a PC with Windows 7 SP1. 它在运行Windows 7 SP1的PC上运行。

var host = WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(pathToContentRoot)
            .UseHttpSys(options =>
            {
                options.Authentication.Schemes = AuthenticationSchemes.None;
                options.Authentication.AllowAnonymous = true;
                options.MaxConnections = null;
                options.MaxRequestBodySize = 30000000;
                options.UrlPrefixes.Add("http://*:5050");
            })
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

if (isService)
{
    host.RunAsService();
}
else
{
    host.Run();
} 

As you can see, I want to listen on port 5050. This is working fine without SSL. 正如你所看到的,我想听5050端口。没有SSL就可以正常工作。

My question is, how can I enable https for my application? 我的问题是,如何为我的应用程序启用https? Again: No IIS, no Domain-Name (no internet connection). 再次:没有IIS,没有域名(没有互联网连接)。 Communication is just inside the internal network, so I want to use a self-signed certificate. 通信就在内部网络内部,因此我想使用自签名证书。

I read the documentation ( HTTP.sys documentation ; Netsh Commands ; New-SelfSignedCertificate ), but there is always something different to my situation (they use Krestel, or it is for using IIS). 我阅读了文档( HTTP.sys文档 ; Netsh命令 ; New-SelfSignedCertificate ),但总有一些与我的情况不同(他们使用Krestel,或者是使用IIS)。 Also, I dont know how to get the App-ID (needed for netsh) for my Application. 另外,我不知道如何为我的应用程序获取App-ID(netsh所需)。 I tryed this: StackOverflow Get GUID but it doesn't work. 我试过这个: StackOverflow获取GUID但它不起作用。

var assembly = typeof(Program).Assembly;

// following line produces: System.IndexOutOfRangeException
var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];

var id = attribute.Value;
Console.WriteLine(id);

So I am a bit confused about all the possabilitys and different configurations. 所以我对所有可能性和不同配置感到有点困惑。 And the docs don't consider my specific case. 文档不考虑我的具体情况。

I created a certificate, and I guess I need to store it on the "my" Store. 我创建了一个证书,我想我需要将它存储在“我的”商店中。 (Where is that? cert:\\LocalMachine\\My) And then I need to assign my Applicaion ID and Port to it. (那是什么?cert:\\ LocalMachine \\ My)然后我需要将我的Applicaion ID和端口分配给它。

But I have no idea how to do that exactly. 但我不知道该怎么做。 Can anyone help? 有人可以帮忙吗?

So I solve the problem in the following way: 所以我通过以下方式解决问题:

First, if you want to know your own GUID, you will get it with the following code: 首先,如果您想知道自己的GUID,可以使用以下代码获取它:

var id = typeof(RuntimeEnvironment).GetTypeInfo().Assembly.GetCustomAttribute<GuidAttribute>().Value;

Create a SelfSigned Certificate 创建自签名证书

Now create a SelfSigned-Certificate (Skip this if you already got one, or purchased one) 现在创建一个SelfSigned-Certificate(如果你已经有一个,或者购买了一个,请跳过它)

  1. Run the following OpenSSL command to generate your private key and public certificate. 运行以下OpenSSL命令以生成您的私钥和公共证书。 Answer the questions and enter the Common Name when prompted. 回答问题并在提示时输入通用名称。

openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem

  1. Combine your key and certificate in a PKCS#12 (P12) bundle: 将您的密钥和证书组合在PKCS#12(P12)包中:

openssl pkcs12 -inkey key.pem -in certificate.pem -export -out certificate.p12 openssl pkcs12 -inkey key.pem -in certificate.pem -export -out certificate.p12

Install the certificate on the client: 在客户端上安装证书:

For Windows 8 and higher: 对于Windows 8及更高版本:

Add Certificate to Windows Cert Store with PowerShell 使用PowerShell将证书添加到Windows Cert Store

PS C:> $certpwd = ConvertTo-SecureString -String "passwort" -Force –AsPlainText PS C:> $ certpwd = ConvertTo-SecureString -String“passwort”-Force -AsPlainText

PS C:> Import-PfxCertificate –FilePath D:\\data\\cert\\certificate.p12 cert:\\localMachine\\my -Password $certpwd PS C:> Import-PfxCertificate -FilePath D:\\ data \\ cert \\ certificate.p12 cert:\\ localMachine \\ my -Password $ certpwd

Get Fingerprint (Hash) of certificate 获取证书的指纹(哈希)

PS C:\\WINDOWS\\system32> dir Cert:\\LocalMachine\\my PS C:\\ WINDOWS \\ system32> dir Cert:\\ LocalMachine \\ my

Install certificate (replace Hash, IP and Port with your values) 安装证书(用您的值替换哈希,IP和端口)

PS C:\\WINDOWS\\system32> $guid = [guid]::NewGuid() PS C:\\ WINDOWS \\ system32> $ guid = [guid] :: NewGuid()

PS C:\\WINDOWS\\system32> $certHash = "A1D...B672E" PS C:\\ WINDOWS \\ system32> $ certHash =“A1D ...... B672E”

PS C:\\WINDOWS\\system32> $ip = "0.0.0.0" PS C:\\ WINDOWS \\ system32> $ ip =“0.0.0.0”

PS C:\\WINDOWS\\system32> $port = "5050" PS C:\\ WINDOWS \\ system32> $ port =“5050”

PS C:\\WINDOWS\\system32> "http add sslcert ipport=$($ip):$port certhash=$certHash appid={$guid}" | PS C:\\ WINDOWS \\ system32>“http add sslcert ipport = $($ ip):$ port certhash = $ certHash appid = {$ guid}”| netsh netsh的

You are done. 你完成了。

For Windows 7 对于Windows 7

Add Certificate to Windows Cert Store (note: use .pem file for this operation, because .p12 file seems to be not supported from certutil) 将证书添加到Windows证书存储区(注意:使用.pem文件执行此操作,因为certutil似乎不支持.p12文件)

.\\certutil.exe -addstore -enterprise -f "Root" C:\\lwe\\cert\\certificate.pem 。\\ certutil.exe -addstore -enterprise -f“Root”C:\\ lwe \\ cert \\ certificate.pem

If his line throws the following error: 如果他的行抛出以下错误:

SSL Certificate add failed, Error 1312 A specified logon session does not exist. SSL证书添加失败,错误1312指定的登录会话不存在。 It may already have been terminated. 它可能已经被终止了。

You have to do the steps manually (please insert the .p12 file when doing it manually, not .pem) : 您必须手动执行这些步骤(请在手动执行时插入.p12文件,而不是.pem):

Run mmc.exe 运行mmc.exe

  • Go to File-> Add/Remove Snap-In 转到文件 - >添加/删除管理单元

  • Choose the Certificates snap-in. 选择“证书”管理单元。

  • Select Computer Account 选择计算机帐户

  • Navigate to: Certificates (Local Computer)\\Personal\\Certificates 导航至:证书(本地计算机)\\个人\\证书

  • Right click the Certificates folder and choose All Tasks -> Import. 右键单击Certificates文件夹,然后选择All Tasks - > Import。

  • Follow the wizard instructions to select the certificate. 按照向导说明选择证书。 Be sure you check the export checkbox during wizard. 请确保在向导期间检查导出复选框。

To get the hash of yor certificate, run the Internet Explorer, press Alt + X and go to Internet Options -> Content -> Certificates. 要获取yor证书的哈希值,请运行Internet Explorer,按Alt + X并转到Internet选项 - >内容 - >证书。 Search your certificate and read the hash. 搜索您的证书并阅读哈希值。

Now you can run the same commands as for Windows 8+: 现在,您可以运行与Windows 8+相同的命令:

Install certificate (replace Hash, IP and Port with your values) 安装证书(用您的值替换哈希,IP和端口)

PS C:\\WINDOWS\\system32> $guid = [guid]::NewGuid() PS C:\\ WINDOWS \\ system32> $ guid = [guid] :: NewGuid()

PS C:\\WINDOWS\\system32> $certHash = "A1D...B672E" PS C:\\ WINDOWS \\ system32> $ certHash =“A1D ...... B672E”

PS C:\\WINDOWS\\system32> $ip = "0.0.0.0" PS C:\\ WINDOWS \\ system32> $ ip =“0.0.0.0”

PS C:\\WINDOWS\\system32> $port = "5050" PS C:\\ WINDOWS \\ system32> $ port =“5050”

PS C:\\WINDOWS\\system32> "http add sslcert ipport=$($ip):$port certhash=$certHash appid={$guid}" | PS C:\\ WINDOWS \\ system32>“http add sslcert ipport = $($ ip):$ port certhash = $ certHash appid = {$ guid}”| netsh netsh的

Edit your Code 编辑您的代码

After all, you have to set the UrlPrefixes to https. 毕竟,您必须将UrlPrefixes设置为https。 So in your Program.cs file you need to have: 因此,在Program.cs文件中,您需要:

var host = WebHost.CreateDefaultBuilder(args)
            .UseContentRoot(pathToContentRoot)
            .UseHttpSys(options =>
            {
                options.Authentication.Schemes = AuthenticationSchemes.None;
                options.Authentication.AllowAnonymous = true;
                options.MaxConnections = null;
                options.MaxRequestBodySize = 30000000;
                options.UrlPrefixes.Add("https://*:5050");
            })
            .UseStartup<Startup>()
            .UseApplicationInsights()
            .Build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM