32

私はIISを使用しておらず、このコンピューターにもインストールされていません。また、コンソールでホストされているWCF RESTサービスにはapp.configファイルもファイルもありません。しかし、ホスト コンソール アプリケーションで HTTPS を実行したいと思います。web.config

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で実行する方法はありますか?

4

2 に答える 2

34
  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)\Microsoft SDKs\Windows\v7.0A\bin です

  2. 証明書をインストールする

    コマンドラインから:

    certmgr.exe -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
    
  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
    
  4. ホストをセットアップする

    HTTPS に設定し、トランスポート セキュリティを有効にします。

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

詳細な参考文献

add sslcert で問題が発生した場合:

于 2012-04-29T16:55:06.720 に答える
4

VS.NET 2010 で新しいコンソール アプリ プロジェクトを作成します。ここで、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 を開き、既定の Web サイトを右クリックして、コンソール アプリで定義したポート番号 (私の場合は 54321) に一致する HTTPS バインディングを追加し、証明書を "localhost" に選択します (上記の手順で作成したもの) を選択し、[OK] をクリックして [閉じる] をクリックします。

ここに画像の説明を入力

次に示すように、コンソール アプリを起動してサービスを実行し、フィドラーを開いて 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 以降の OS の netsh ツールと winxp の httpcfg を使用して、ssl 証明書の http ポート マッピングを行います。

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

certhash -- 上記で作成した証明書の拇印 ID。拇印 ID は、Microsoft 管理コンソールを開いて取得できます - ローカル マシン上のコンピューター アカウントの証明書ストアのスナップインを追加/削除し、個人用ストアに移動して証明書を見つけます (上記のようにインストールされていると仮定します)。証明書をダブルクリックし、詳細タブに移動して、プロパティの 1 つとして拇印 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

以下のように netsh コマンドを使用して、ポートへの ssl 証明書のマッピングを削除できます。

c:\> netsh http delete sslcert ipport:0.0.0.0:54321
于 2012-05-04T15:50:16.913 に答える