来自控制台应用程序的HTTPS?

Kir*_*ite 31 c# rest https wcf web-services

我没有使用IIS,甚至没有安装在这台计算机上.我的控制台托管的WCF REST服务中也没有任何app.config文件或web.config文件.但我想尝试在主机控制台应用程序上运行HTTPS:

class Program
{
    static void Main(string[] args)
    {
        string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
        //WebHttpBinding binding = new WebHttpBinding();
        //binding.Security.Mode = WebHttpSecurityMode.Transport;
        host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
        host.Open();

        Console.WriteLine("Host opened");
        Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

有没有办法让我的服务在HTTPS中运行?

Pet*_*tin 31

  1. 创建并安装根颁发机构和HTTPS证书

    以管理员身份打开命令提示

    创建文件夹C:\Certs并导航到它.

    #Root Authority
    makecert.exe -r -pe -n "CN=My Root Authority" -ss CA -sr LocalMachine -a sha1 -sky signature -cy authority -sv CA.pvk CA.cer
    
    #Certificate
    makecert.exe -pe -n "CN=localhost" -a sha1 -sky exchange -eku 1.3.6.1.5.5.7.3.1 -ic CA.cer -iv CA.pvk -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -sv server.pvk server.cer
    
    #key
    pvk2pfx.exe -pvk server.pvk -spc server.cer -pfx server.pfx
    
    Run Code Online (Sandbox Code Playgroud)

    **makecert和pvk2pfx的默认位置是C:\ Program Files(x86)\ Microsoft SDKs\Windows\v7.0A\bin

  2. 安装证书

    从命令行:

    certmgr.exe -add CA.cer -r LocalMachine -s CertificateAuthority

    certmgr.exe -add server.pfx -r LocalMachine -s My -all

    来自MMC:

    打开MMC通过转到命令提示符并输入MMC.这将打开空白MMC控制台.单击添加/删除管理单元.添加证书并选择计算机帐户/本地计算机.

    导航到中级证书颁发机构/证书.右键单击并选择导入.导航到您创建CA.cer文件的文件夹,然后单击以导入.

    导航到"个人/证书",然后右键单击"导入".找到您的server.pfx文件(您需要从可用扩展名列表中选择PFX)并导入此文件.完成后,双击打开证书,并在详细信息下记下其指纹.将其粘贴到记事本中?在开头删除额外内容并删除空格.

    要获取服务器指纹证书,可以在PowerShell中运行:

    $getThumb = Get-ChildItem -path cert:\LocalMachine\TrustedPeople | where { $_.Subject -match "CN=localhost" }
    $getThumb.thumbprint
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用netsh注册和映射WCF端口

    映射到WCF端口

    netsh http add sslcert ipport=0.0.0.0:8000 certhash=73269e9b554f58d75e77880f5ff72b50c8d724ee appid={e2eaacd9-92e6-43cc-b51c-7a7887149607}
    
    appid - any GUID
    certhas - this is the thumb print from the step 2
    
    Run Code Online (Sandbox Code Playgroud)
  4. 设置您的主机

    设置为HTTPS并启用传输安全性:

    string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
    var binding = new WebHttpBinding();
    binding.Security.Mode = WebHttpSecurityMode.Transport;
    
    Run Code Online (Sandbox Code Playgroud)

详细参考

如果你遇到添加sslcert的问题: