次の方法で共有


メッセージ セキュリティ ユーザー名

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

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

このサンプルでは、次のことも示します。

  • Windows アカウントへの既定のマッピングにより、追加の承認が行えるようにします。

  • サービス コードから呼び出し元の ID 情報にアクセスする方法。

サービスは、サービスと通信するための単一のエンドポイントを公開します。これは、構成ファイル Web.configを使用して定義されます。エンドポイントは、アドレス、バインディング、およびコントラクトで構成されます。 バインディングは標準の <wsHttpBinding> で構成され、既定ではメッセージ セキュリティが使用されます。 このサンプルでは、クライアント ユーザー名認証を使用するように標準の <wsHttpBinding> を設定します。 この動作では、ユーザー資格情報をサービス認証に使用することを指定します。 サーバー証明書には、findValue<> の属性と同じサブジェクト名の値が含まれている必要があります。

<system.serviceModel>
  <protocolMapping>
    <add scheme="http" binding="wsHttpBinding" />
  </protocolMapping>
  <bindings>
    <wsHttpBinding>
      <!--
      This configuration defines the security mode as Message and
      the clientCredentialType as Username.
      By default, Username authentication attempts to authenticate the provided
      username as a Windows computer or domain account.
      -->
      <binding>
        <security mode="Message">
          <message clientCredentialType="UserName"/>
        </security>
      </binding>
    </wsHttpBinding>
  </bindings>

  <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true.-->
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <!--
      The serviceCredentials behavior allows one to define a service certificate.
      A service certificate is used by the service to authenticate itself to the client 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" />
        </serviceCredentials>
        <serviceMetadata httpGetEnabled="True"/>
        <serviceDebug includeExceptionDetailInFaults="False" />
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>

クライアント エンドポイントの構成は、サービス エンドポイント、バインディング、コントラクトの絶対アドレスで構成されます。 クライアント バインドは、適切な securityModeauthenticationModeで構成されます。 コンピューター間のシナリオで実行する場合は、それに応じてサービス エンドポイント アドレスを変更する必要があります。

<system.serviceModel>
  <client>
    <endpoint address="http://localhost/servicemodelsamples/service.svc"
              binding="wsHttpBinding"
              bindingConfiguration="Binding1"
              behaviorConfiguration="ClientCredentialsBehavior"
              contract="Microsoft.ServiceModel.Samples.ICalculator" />
  </client>

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

  <!--For debugging purposes set the includeExceptionDetailInFaults attribute to true.-->
  <behaviors>
    <endpointBehaviors>
      <behavior name="ClientCredentialsBehavior">
        <!--
      Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
      is in the user's Trusted People store, then it is 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.
      -->
        <clientCredentials>
          <serviceCertificate>
            <authentication certificateValidationMode="PeerOrChainTrust" />
          </serviceCertificate>
        </clientCredentials>
      </behavior>
    </endpointBehaviors>
  </behaviors>
</system.serviceModel>

クライアント実装では、使用するユーザー名とパスワードを設定します。

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

// Configure client with valid computer or domain account (username,password).
client.ClientCredentials.UserName.UserName = username;
client.ClientCredentials.UserName.Password = password.ToString();

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

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

MyMachine\TestAccount
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.

MessageSecurity サンプルに含まれる Setup.bat バッチ ファイルを使用すると、証明書ベースのセキュリティを必要とするホストされたアプリケーションを実行するように、関連する証明書を使用してサーバーを構成できます。 バッチ ファイルは、2 つのモードで実行できます。 単一コンピューター モードでバッチ ファイルを実行するには、コマンド ラインで「 setup.bat 」と入力します。 サービス モードで実行するには、setup.bat service を入力します。 このモードは、複数のコンピューターでサンプルを実行するときに使用します。 詳細については、このトピックの最後にあるセットアップ手順を参照してください。

バッチ ファイルのさまざまなセクションの概要を次に示します。

  • サーバー証明書の作成

    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 service など) で実行される場合、%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 アカウント名を地域に相当する名前に置き換える必要があります。

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

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

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

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

  1. パスに、Makecert.exe と FindPrivateKey.exe が配置されているフォルダーが含まれていることを確認します。

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

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

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

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

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

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

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

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

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

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

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

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

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

  8. クライアント コンピューター上の Client.exe.config ファイルで、サービスの新しいアドレスと一致するようにエンドポイントのアドレス値を変更します。

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

  10. クライアント コンピューターで、コマンド プロンプトから 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.