次の方法で共有


メッセージ セキュリティ証明書

MessageSecurity サンプル では、クライアントの X.509 v3 証明書認証で WS-Security を使用し、サーバーの X.509 v3 証明書を使用したサーバー認証を必要とするアプリケーションを実装する方法を示します。 このサンプルでは、クライアントとサーバーの間のすべてのアプリケーション メッセージが署名および暗号化されるように、既定の設定を使用します。 このサンプルは、WSHttpBinding に基づいており、クライアント コンソール プログラムと、インターネット インフォメーション サービス (IIS) によってホストされるサービス ライブラリで構成されています。 このサービスは、要求/応答通信パターンを定義するコントラクトを実装します。

手記

このサンプルのセットアップ手順とビルド手順は、このトピックの最後にあります。

このサンプルでは、次のサンプル コードに示すように、構成を使用して認証を制御する方法と、セキュリティ コンテキストから呼び出し元の ID を取得する方法を示します。

public class CalculatorService : ICalculator
{
    public string GetCallerIdentity()
    {
        // The client certificate is not mapped to a Windows identity by default.
        // ServiceSecurityContext.PrimaryIdentity is populated based on the information
        // in the certificate that the client used to authenticate itself to the service.
        return ServiceSecurityContext.Current.PrimaryIdentity.Name;
    }
    ...
}

サービスは、サービスと通信するための 1 つのエンドポイントと、構成ファイル (Web.config) を使用して定義された WS-MetadataExchange プロトコルを使用してサービスの WSDL ドキュメントを公開するための 1 つのエンドポイントを公開します。 エンドポイントは、アドレス、バインディング、およびコントラクトで構成されます。 バインディングは、wsHttpBinding<>標準で構成されます。既定ではメッセージ セキュリティが使用されます。 このサンプルでは、clientCredentialType 属性を証明書に設定して、クライアント認証を要求します。

<system.serviceModel>
    <protocolMapping>
      <add scheme="http" binding="wsHttpBinding"/>
    </protocolMapping>
    <bindings>
      <wsHttpBinding>
        <!--
        This configuration defines the security mode as Message and
        the clientCredentialType as Certificate.
        -->
        <binding>
          <security mode ="Message">
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true-->
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
          <!--
        The serviceCredentials behavior allows one to define a service certificate.
        A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
        This configuration references the "localhost" certificate installed during the setup instructions.
        -->
          <serviceCredentials>
            <serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
              <!--
            Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
            is in the user's Trusted People store, then it will be trusted without performing a
            validation of the certificate's issuer chain. This setting is used here for convenience so that the
            sample can be run without having to have certificates issued by a certification authority (CA).
            This setting is less secure than the default, ChainTrust. The security implications of this
            setting should be carefully considered before using PeerOrChainTrust in production code.
            -->
              <authentication certificateValidationMode="PeerOrChainTrust" />
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

この動作では、クライアントがサービスを認証するときに使用されるサービスの資格情報を指定します。 サーバー証明書のサブジェクト名は、findValue 要素の < 属性で指定されます。

<!--For debugging purposes, set the includeExceptionDetailInFaults attribute to true.-->
<behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="False" />
          <!--
        The serviceCredentials behavior allows one to define a service certificate.
        A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
        This configuration references the "localhost" certificate installed during the setup instructions.
        -->
          <serviceCredentials>
            <serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
              <!--
            Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
            is in the user's Trusted People store, then it will be trusted without performing a
            validation of the certificate's issuer chain. This setting is used here for convenience so that the
            sample can be run without having to have certificates issued by a certification authority (CA).
            This setting is less secure than the default, ChainTrust. The security implications of this
            setting should be carefully considered before using PeerOrChainTrust in production code.
            -->
              <authentication certificateValidationMode="PeerOrChainTrust" />
            </clientCertificate>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>

クライアント エンドポイントの構成は、サービス エンドポイント、バインディング、コントラクトの絶対アドレスで構成されます。 クライアント バインドは、適切なセキュリティ モードと認証モードで構成されます。 コンピューター間のシナリオで実行する場合は、それに応じてサービス エンドポイント アドレスが変更されていることを確認します。

<system.serviceModel>
    <client>
      <!-- Use a behavior to configure the client certificate to present to the service. -->
      <endpoint address="http://localhost/servicemodelsamples/service.svc" binding="wsHttpBinding" bindingConfiguration="Binding1" behaviorConfiguration="ClientCertificateBehavior" contract="Microsoft.Samples.Certificate.ICalculator"/>
    </client>

    <bindings>
      <wsHttpBinding>
        <!--
        This configuration defines the security mode as Message and
        the clientCredentialType as Certificate.
        -->
        <binding name="Binding1">
          <security mode="Message">
            <message clientCredentialType="Certificate"/>
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
...
</system.serviceModel>

クライアントの実装では、構成ファイルまたはコードを使用して、使用する証明書を設定できます。 次の例は、構成ファイルで使用する証明書を設定する方法を示しています。

<system.serviceModel>
  ...

<behaviors>
      <endpointBehaviors>
        <behavior name="ClientCertificateBehavior">
          <!--
        The clientCredentials behavior allows one to define a certificate to present to a service.
        A certificate is used by a client to authenticate itself to the service and provide message integrity.
        This configuration references the "client.com" certificate installed during the setup instructions.
        -->
          <clientCredentials>
            <clientCertificate findValue="client.com" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName"/>
            <serviceCertificate>
              <!--
            Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
            is in the user's Trusted People store, then it will be trusted without performing a
            validation of the certificate's issuer chain. This setting is used here for convenience so that the
            sample can be run without having to have certificates issued by a certificate authority (CA).
            This setting is less secure than the default, ChainTrust. The security implications of this
            setting should be carefully considered before using PeerOrChainTrust in production code.
            -->
              <authentication certificateValidationMode="PeerOrChainTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

</system.serviceModel>

次の例は、プログラムでサービスを呼び出す方法を示しています。

// Create a client.
CalculatorClient client = new CalculatorClient();

// Call the GetCallerIdentity service operation.
Console.WriteLine(client.GetCallerIdentity());
...
//Closing the client gracefully closes the connection and cleans up resources.
client.Close();

サンプルを実行すると、操作要求と応答がクライアント コンソール ウィンドウに表示されます。 クライアント ウィンドウで Enter キーを押して、クライアントをシャットダウンします。

CN=client.com
Add(100,15.99) = 115.99
Subtract(145,76.54) = 68.46
Multiply(9,81.25) = 731.25
Divide(22,7) = 3.14285714285714
Press <ENTER> to terminate client.

メッセージ セキュリティ サンプルに含まれる Setup.bat バッチ ファイルを使用すると、証明書ベースのセキュリティを必要とするホストされたアプリケーションを実行するように、関連する証明書を使用してクライアントとサーバーを構成できます。 バッチ ファイルは、3 つのモードで実行できます。 単一コンピューター モードで実行するには、Visual Studio の開発者コマンド プロンプトで setup.bat を入力します。サービスモードタイプ setup.bat サービス用;クライアント モードの種類 setup.bat クライアント。 複数のコンピューターでサンプルを実行する場合は、クライアントモードとサーバー モードを使用します。 詳細については、このトピックの最後にあるセットアップ手順を参照してください。 次に、適切な構成で実行するように変更できるように、バッチ ファイルのさまざまなセクションの概要を示します。

  • クライアント証明書の作成。

    バッチ ファイル内の次の行は、クライアント証明書を作成します。 指定されたクライアント名は、作成された証明書のサブジェクト名で使用されます。 証明書は、My ストアの場所の CurrentUser ストアに格納されます。

    echo ************
    echo making client cert
    echo ************
    makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%CLIENT_NAME% -sky exchange -pe
    
  • クライアント証明書をサーバーの信頼された証明書ストアにインストールする。

    バッチ ファイル内の次の行は、サーバーが関連する信頼または信頼しない決定を行うことができるように、クライアント証明書をサーバーの TrustedPeople ストアにコピーします。 TrustedPeople ストアにインストールされている証明書を Windows Communication Foundation (WCF) サービスによって信頼できるようにするには、クライアント証明書検証モードを PeerOrChainTrust または PeerTrustに設定する必要があります。 構成ファイルを使用してこれを行う方法については、前のサービス構成サンプルを参照してください。

    echo ************
    echo copying client cert to server's LocalMachine store
    echo ************
    certmgr.exe -add -r CurrentUser -s My -c -n %CLIENT_NAME% -r LocalMachine -s TrustedPeople
    
  • サーバー証明書の作成。

    Setup.bat バッチ ファイルの次の行は、使用するサーバー証明書を作成します。

    echo ************
    echo Server cert setup starting
    echo %SERVER_NAME%
    echo ************
    echo making server cert
    echo ************
    makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe
    

    %SERVER_NAME% 変数は、サーバー名を指定します。 証明書は LocalMachine ストアに格納されます。 Setup.bat バッチ ファイルがサービスの引数 (setup.bat サービスなど) で実行される場合、%SERVER_NAME% にはコンピューターの完全修飾ドメイン名が含まれます。 それ以外の場合は、既定で localhost になります。

  • クライアントの信頼された証明書ストアへのサーバー証明書のインストール。

    次の行は、サーバー証明書をクライアントの信頼されたユーザー ストアにコピーします。 Makecert.exe によって生成された証明書はクライアント システムによって暗黙的に信頼されないため、この手順が必要です。 クライアントの信頼されたルート証明書 (Microsoft が発行した証明書など) にルート化された証明書が既にある場合、クライアント証明書ストアにサーバー証明書を設定するこの手順は必要ありません。

    certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
    
  • 証明書の秘密キーに対するアクセス許可の付与。

    Setup.bat ファイルの次の行は、localMachine ストアに格納されているサーバー証明書を、ASP.NET ワーカー プロセス アカウントからアクセスできるようにします。

    echo ************
    echo setting privileges on server certificates
    echo ************
    for /F "delims=" %%i in ('"%ProgramFiles%\ServiceModelSampleTools\FindPrivateKey.exe" My LocalMachine -n CN^=%SERVER_NAME% -a') do set PRIVATE_KEY_FILE=%%i
    set WP_ACCOUNT=NT AUTHORITY\NETWORK SERVICE
    (ver | findstr /C:"5.1") && set WP_ACCOUNT=%COMPUTERNAME%\ASPNET
    echo Y|cacls.exe "%PRIVATE_KEY_FILE%" /E /G "%WP_ACCOUNT%":R
    iisreset
    

    手記

    米国以外のユーザーを使用している場合Windows の英語版では、Setup.bat ファイルを編集し、"NT AUTHORITY\NETWORK SERVICE" アカウント名を地域に相当する名前に置き換える必要があります。

手記

このバッチ ファイルで使用されるツールは、C:\Program Files\Microsoft Visual Studio 8\Common7\tools または C:\Program Files\Microsoft SDK\Windows\v6.0\bin にあります。 これらのディレクトリの 1 つがシステム パスに存在する必要があります。 Visual Studio がインストールされている場合、パスでこのディレクトリを取得する最も簡単な方法は、Visual Studio の開発者コマンド プロンプトを開く方法です。 [スタート] をクリックしてから、[すべてのプログラム][Visual Studio 2012][ツール] の順に選択します。 このコマンド プロンプトには、適切なパスが既に構成されています。 それ以外の場合は、パスに適切なディレクトリを手動で追加する必要があります。

サンプルを設定、ビルド、実行するには

  1. Windows Communication Foundation サンプル One-Time セットアップ手順を実行していることを確認します。

  2. ソリューションの C# または Visual Basic .NET エディションをビルドするには、「Windows Communication Foundation サンプルのビルド」の手順に従います。

同じコンピューターでサンプルを実行するには

  1. 管理者特権で Visual Studio の開発者コマンド プロンプトを開き、サンプルのインストール フォルダーから Setup.bat 実行します。 これにより、サンプルの実行に必要なすべての証明書がインストールされます。

    手記

    Setup.bat バッチ ファイルは、Visual Studio の開発者コマンド プロンプトから実行するように設計されています。 パス環境変数が SDK がインストールされているディレクトリを指している必要があります。 この環境変数は、Visual Studio の開発者コマンド プロンプト (2010) 内で自動的に設定されます。

  2. http://localhost/servicemodelsamples/service.svcアドレスを入力して、ブラウザーを使用してサービスへのアクセスを確認します。

  3. \client\bin から Client.exe を起動します。 クライアント アクティビティがクライアント コンソール アプリケーションに表示されます。

  4. クライアントとサービスが通信できない場合は、「WCF サンプルのトラブルシューティングのヒント」を参照してください。

複数のコンピューターでサンプルを実行するには

  1. サービス コンピューター上にディレクトリを作成します。 インターネット インフォメーション サービス (IIS) 管理ツールを使用して、このディレクトリの servicemodelsamples という名前の仮想アプリケーションを作成します。

  2. サービス プログラム ファイルを \inetpub\wwwroot\servicemodelsamples からサービス コンピューター上の仮想ディレクトリにコピーします。 \bin サブディレクトリ内のファイルをコピーしてください。 また、Setup.bat、Cleanup.bat、および ImportClientCert.bat ファイルをサービス コンピューターにコピーします。

  3. クライアント コンピューター上にクライアント バイナリ用のディレクトリを作成します。

  4. クライアント プログラム ファイルをクライアント コンピューター上のクライアント ディレクトリにコピーします。 また、Setup.bat、Cleanup.bat、および ImportServiceCert.bat ファイルをクライアントにコピーします。

  5. サーバーで、管理者特権 setup.bat 使用して、Visual Studio の開発者コマンド プロンプトでサービス を実行します。 サービス 引数を指定して setup.bat を実行すると、コンピューターの完全修飾ドメイン名を持つサービス証明書が作成され、サービス証明書が Service.cer という名前のファイルにエクスポートされます。

  6. Web.config を編集して、新しい証明書名(コンピューターの完全修飾ドメイン名と同じ)が findValueの < 属性に反映されるようにします。

  7. Service.cer ファイルをサービス ディレクトリからクライアント コンピューター上のクライアント ディレクトリにコピーします。

  8. クライアントで、管理者特権 setup.bat 使用して、Visual Studio の開発者コマンド プロンプトでクライアント を実行します。 client 引数を指定して setup.bat を実行すると、client.com という名前のクライアント証明書が作成され、クライアント証明書が Client.cer という名前のファイルにエクスポートされます。

  9. クライアント コンピューター上の Client.exe.config ファイルで、サービスの新しいアドレスと一致するようにエンドポイントのアドレス値を変更します。 これを行うには、localhost をサーバーの完全修飾ドメイン名に置き換えます。

  10. Client.cer ファイルをクライアント ディレクトリからサーバー上のサービス ディレクトリにコピーします。

  11. クライアントで、管理者特権を持つ Visual Studio の開発者コマンド プロンプトで ImportServiceCert.bat を実行します。 これにより、Service.cer ファイルから CurrentUser - TrustedPeople ストアにサービス証明書がインポートされます。

  12. サーバーで、管理特権を持つ Visual Studio の開発者コマンド プロンプトで ImportClientCert.bat を実行します。 これにより、Client.cer ファイルから LocalMachine - TrustedPeople ストアにクライアント証明書がインポートされます。

  13. クライアント コンピューターで、コマンド プロンプト ウィンドウから Client.exe を起動します。 クライアントとサービスが通信できない場合は、「WCF サンプルのトラブルシューティングのヒント」を参照してください。

サンプルの実行後にクリーンアップするには

  • サンプルの実行が完了したら、samples フォルダーで Cleanup.bat を実行します。

    手記

    このスクリプトは、コンピューター間でこのサンプルを実行するときに、クライアント上のサービス証明書を削除しません。 コンピューター間で証明書を使用する Windows Communication Foundation (WCF) サンプルを実行している場合は、CurrentUser - TrustedPeople ストアにインストールされているサービス証明書を必ずクリアしてください。 これを行うには、次のコマンドを使用します。 certmgr -del -r CurrentUser -s TrustedPeople -c -n <Fully Qualified Server Machine Name> 例: certmgr -del -r CurrentUser -s TrustedPeople -c -n server1.contoso.com.