[C#.NET][WCF] wsHttpBinding @self-host 的安全性–使用 X509 Certificate 驗証

  • 3606
  • 0
  • WCF
  • 2013-10-25

[C#.NET][WCF] wsHttpBinding @self-host 的安全性–使用 X509 Certificate 驗証

[WCF] wsHttpBinding host 的安全性–使用 Windows UserName 驗証 上篇採用了Windows User Name 的驗証方式,這篇則來演練如何使用 X509 Certificate 驗証

同上篇一樣,在 Server 端要準備好憑證跟防火牆

在Visual Studio Command Prompt (2010)輸入:

makecert -pe -n CN=WCFRoot -ss Root -sr LocalMachine -a sha1 -sky signature
makecert.exe -sr LocalMachine -ss My -a sha1 -n CN=WCFServer -sky exchange -pe -is Root -ir LocalMachine -in WCFRoot

 

安全性設定演練如下:

Step1.把 Server 端的憑證匯出給 Client 使用

Step2.設定 WcfServiceLibrary 專案的 App.Config

image

 

新增一個wsHttpBinding,並命名為設定 wsHttpBinding.Config

image

 

設定Certificate

image

 

將 Configuration命名為WcfServiceLibrary.ServiceBehavior,並增加serviceCredentials

image

 

設定憑證資訊

image

 

憑證驗證設為None

image

 

套用wsHttpBinding.Config

image

 

套用WcfServiceLibrary.ServiceBehavior

image

 

存檔,

設定完成的App.Config如下:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="wsHttpBinding.Config">
          <security>
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="WcfServiceLibrary.ServiceBehavior"
        name="WcfServiceLibrary.Service">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsHttpBinding.Config"
          contract="WcfServiceLibrary.IService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:168" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServiceLibrary.ServiceBehavior">
          <serviceCredentials>
            <clientCertificate>
              <authentication certificateValidationMode="None" revocationMode="NoCheck" />
            </clientCertificate>
            <serviceCertificate findValue="CN=WCFServer" />
            <userNameAuthentication userNamePasswordValidationMode="Windows" />
          </serviceCredentials>
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

按下F5,執行看看

image

 

Step4.Client加入參考

開一個新的Winform專案

SNAGHTML1a2254bd

 

輸入遠端WCF Server位置,找到服務後按下OK

SNAGHTML1a24c895

 

Step5.修改 Client 專案的App.Config

SNAGHTML1a261869

 

新增一個EndPoint

SNAGHTML1a267c0b

 

替EndPoint命名為EndPointBehavior.Config,然後增加一個clientCredentials

SNAGHTML1a27fd5a

 

 

 

輸入憑證資訊,這個憑證是從Server上來的

SNAGHTML1a2adb1b

 

設定驗証模式

SNAGHTML1a2c023a

 

套用EndPointBehavior.Config

 

SNAGHTML1a2d0bdb

 

SNAGHTML1a63faec

存檔

就可以看到以下App.Config


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="EndPointBehavior.Config">
          <clientCredentials>
            <clientCertificate findValue="CN=WCFServer" storeLocation="LocalMachine" />
            <serviceCertificate>
              <authentication certificateValidationMode="None" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <wsHttpBinding>
        <binding name="WSHttpBinding_IService">
          <security>
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="http://localhost:168/" behaviorConfiguration="EndPointBehavior.Config"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
        contract="WcfServiceLibrary.IService" name="WSHttpBinding_IService">
        <identity>
          <dns value="WCFServer" />
        </identity>
      </endpoint>
    </client>
  </system.serviceModel>
</configuration>


將endPoint Address修改為遠端位置
SNAGHTML1a64689c

 

Step6.為Client加上程式碼

設計以下UI

SNAGHTML1a2ea971

 

加入以下片斷


private ServiceClient _client = new ServiceClient();

private void button_GetResult_Click(object sender, EventArgs e)
{
    this.button_GetResult.Enabled = false;
    string result = "";
    try
    {
        result = this._client.SayHello(textBox_UserName.Text);
        MessageBox.Show(result);
    }
    catch (TimeoutException exception)
    {
        var msg = string.Format(exception.Message);
        this._client.Abort();
        MessageBox.Show(msg);
    }
    catch (CommunicationException exception)
    {
        var msg = string.Format(exception.Message);
        this._client.Abort();
        MessageBox.Show(msg);
    }
    this.button_GetResult.Enabled = true;
}

按下F5,取得正確的結果

SNAGHTML1a31440b

 

以上是X509 Certificate 驗証設定演示。

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo