从控制台应用程序HTTPS?(HTTPS from a console application?)

2019-06-23 21:20发布

我不使用IIS ,它甚至没有在这台计算机上安装。 我也没有任何app.config文件或web.config的文件在我的控制台托管WCF REST服务。 但我想尝试并获得在主机控制台应用程序运行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();

有没有一种方法我可以有我的服务运行HTTPS ?

Answer 1:

  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 

    **为makecert和pvk2pfx默认位置为C:\ Program Files文件(x86)的\微软的SDK \的Windows \ v7.0A \ BIN

  2. 安装证书

    在命令行:

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

    certmgr.exe -add server.pfx -r -s LOCALMACHINE我-all

    从MMC:

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

    导航到中间证书颁发机构/证书。 右击并选择进口。 导航到你有creatd CA.cer文件,然后单击导入的文件夹。

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

    要获得服务器指纹的证书,你可以在运行这个PowerShell的 :

     $getThumb = Get-ChildItem -path cert:\LocalMachine\TrustedPeople | where { $_.Subject -match "CN=localhost" } $getThumb.thumbprint 
  3. 注册和地图WCF端口的netsh

    地图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 
  4. 设置你的主机

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

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

详细参考

  • 如何创建和安装在WCF运输安全发展在临时证书 (MSDN)

  • 配置HTTP和HTTPS (MSDN)

  • 如何配置使用SSL证书端口 (MSDN)

如果你碰上有附加的sslcert问题:

  • 堆栈溢出问题, 使用SSL和WCF自托管-不能绑定证书到端口

  • 堆栈溢出问题使用Netsh,绑定一个SSL证书端口号失败

  • 堆栈溢出的问题上WCF服务,不使用IIS证书



Answer 2:

在2010年VS.NET创建一个新的控制台应用程序项目现在添加引用的DLL的

 a.  System.ServiceModel
 b.  System.ServiceModel.Web
 c.  System.Runtime.Serialization

所述的Program.cs Main方法具有下面的代码

public class Program
    {
        public static void Main(string[] args)
        {
            Uri baseAddress = new Uri("https://"+Environment.MachineName+":54321/hello");
            using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
            {                
                WebHttpBinding web = new WebHttpBinding();
                web.Security.Mode = WebHttpSecurityMode.Transport;                
                host.AddServiceEndpoint(typeof(IHelloWorldService), web, "").Behaviors.Add(new WebHttpBehavior());                                
                host.Credentials.ServiceCertificate.Certificate = (X509Certificate2)GetX509Certificate();                               
                host.Open();
                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();                
                host.Close();
            }
        }

        private static X509Certificate GetX509Certificate()
        {
            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate certificate = null;
            X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, "localhost", false);            
            if (cers.Count > 0)
            {
                certificate = cers[0];
            }
            store.Close();
            return certificate;
        }
    }

[ServiceContract]
    public interface IHelloWorldService
    {
        [WebGet(UriTemplate="SayHello/{name}")]
        string SayHello(string name);
    }

    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }

现在,我们通过创建以下命令的批处理文件(从MSDN获得)和VS.NET命令提示符下执行它创建证书:

echo off
setlocal

call :setscriptvariables %1
IF NOT DEFINED SUPPORTED_MODE call :displayusage
IF DEFINED SUPPORTED_MODE call :cleancerts
IF DEFINED SETUP_SERVICE call :setupservice
IF DEFINED SETUP_CLIENT call :setupclient
GOTO end

:cleancerts
REM cleans up certs from previous runs.    
certmgr.exe -del -r CurrentUser -s My -c -n %CLIENT_NAME%
certmgr.exe -del -r CurrentUser -s TrustedPeople -c -n localhost
certmgr.exe -del -r LocalMachine -s My -c -n localhost
certmgr.exe -del -r LocalMachine -s TrustedPeople -c -n %CLIENT_NAME%
certmgr.exe -put -r LocalMachine -s My -c -n %COMPUTER_NAME% computer.cer
IF %ERRORLEVEL% EQU 0 (
   DEL computer.cer       
   pause
   certmgr.exe -del -r LocalMachine -s My -c -n %COMPUTER_NAME%
)

:cleanupcompleted   

GOTO :EOF

:setupclient
makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%CLIENT_NAME% -sky exchange -pe

IF DEFINED EXPORT_CLIENT (        
    certmgr.exe -put -r CurrentUser -s My -c -n %CLIENT_NAME% client.cer
) ELSE (        
    certmgr.exe -add -r CurrentUser -s My -c -n %CLIENT_NAME% -r LocalMachine -s TrustedPeople
)
GOTO :EOF

:setupservice
makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe

IF DEFINED EXPORT_SERVICE (       
    certmgr.exe -put -r LocalMachine -s My -c -n %SERVER_NAME% service.cer
) ELSE (        
    certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
)
GOTO :EOF

:setscriptvariables
REM Parses the input to determine if we are setting this up for a single machine, client, or server
REM sets the appropriate name variables
call :setcomputername
IF [%1]==[] CALL :singlemachine
IF [%1]==[service] CALL :service
IF [%1]==[client] CALL :client

set CLIENT_NAME=client.com

GOTO :EOF

:singlemachine    
SET SUPPORTED_MODE=1
SET SETUP_CLIENT=1
SET SETUP_SERVICE=1
SET SERVER_NAME=localhost
GOTO :EOF

:service    
SET SUPPORTED_MODE=1
SET SETUP_SERVICE=1
SET EXPORT_SERVICE=1
SET SERVER_NAME=%COMPUTER_NAME%
GOTO :EOF

:client   
SET SUPPORTED_MODE=1
SET SETUP_CLIENT=1
SET EXPORT_CLIENT=1
GOTO :EOF

:setcomputername
REM Puts the Fully Qualified Name of the Computer into a variable named COMPUTER_NAME
for /F "delims=" %%i in ('cscript /nologo GetComputerName.vbs') do set COMPUTER_NAME=%%i
GOTO :EOF

:displayusage
ECHO Correct usage:
ECHO     Single Machine - Setup.bat
ECHO     Client Machine - Setup.bat client
ECHO     Service Machine - Setup.bat service
:end

现在,打开Microsoft管理控制台,然后选择文件 - >添加/删除管理单元添加的证书 - 当前用户和证书 - 本地计算机商店

导航到证书 - 本地计算机上的个人商店,寻找一个服务器证书为localhost(自签名)创建和安装。

现在,打开默认网站上的IIS,然后右键单击要添加HTTPS绑定到它与您在控制台应用程序定义(为我公司54321)的端口号匹配和选择证书是“本地主机”(在那证书在上述步骤中创建),并单击“确定”和“关闭”

现在开始您的控制台应用程序,让您的业务正常运行,现在开放的小提琴手,如图所示执行GET请求:

GET https://rajeshwin7:54321/hello/sayhello/rajesh HTTP/1.1
User-Agent: Fiddler
Host: rajeshwin7:54321

现在你回来的回应如下:

HTTP/1.1 200 OK
Content-Length: 90
Content-Type: application/xml; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 04 May 2012 14:51:25 GMT

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">Hello, rajesh</string>

当没有IIS存在打开命令提示并输入在命令提示使用winvista和上述操作系统Netsh工具做用于SSL证书一个http端口映射下面和httpcfg为WINXP。

C:\> netsh http add sslcert ipport=0.0.0.0:54321 certhash=6797aea29440de9389bc636e15a35b741d8c22a3 appid={2e80948d-9ae6-42c9-ad33-294929333965}

CERTHASH - 上面创建的证书的指纹编号。 指纹ID可以通过打开Microsoft管理控制台获得 - 添加/删除管理单元在本地计算机上的计算机帐户的证书存储,然后导航到个人商店找到证书(假设上面给出已安装),然后证书上双击并导航到细节选项卡,找到指纹ID作为属性之一(只需复制它在上面netsh命令使用通过删除空格)

APPID - 与您的应用程序,它可以在你的assembly.cs找到文件在您的项目属性文件夹,如下图所示相关的GUID:

现在清理证书创建具有以下命令的bathc文件,然后使用Vs.NET命令提示符下执行:

echo off
setlocal
set CLIENT_NAME=client.com
call :setcomputername
call :cleancerts
DEL client.cer > NUL 2>&1
DEL service.cer > NUL 2>&1
GOTO end

:cleancerts
REM cleans up certs from previous runs.
certmgr.exe -del -r CurrentUser -s My -c -n %CLIENT_NAME%
certmgr.exe -del -r CurrentUser -s TrustedPeople -c -n localhost

certmgr.exe -del -r LocalMachine -s My -c -n localhost
certmgr.exe -del -r LocalMachine -s TrustedPeople -c -n %CLIENT_NAME%
certmgr.exe -put -r LocalMachine -s My -c -n %COMPUTER_NAME% computer.cer
IF %ERRORLEVEL% EQU 0 (
   DEL computer.cer
   pause
   certmgr.exe -del -r LocalMachine -s My -c -n %COMPUTER_NAME%
)

:cleanupcompleted
GOTO :EOF

:setcomputername
REM Puts the Fully Qualified Name of the Computer into a variable named COMPUTER_NAME
for /F "delims=" %%i in ('cscript /nologo GetComputerName.vbs') do set COMPUTER_NAME=%%i
GOTO :EOF

:end

您可以删除SSL证书映射到使用netsh命令,如下端口:

c:\> netsh http delete sslcert ipport:0.0.0.0:54321


文章来源: HTTPS from a console application?