WCF basicHttpBinding之Message Security Mode

前面的文章《WCF Security基本概念》介紹了WCF的security mode,簡單說Transport是transport級別上的加密,Message是message級別上的加密,參見下圖:

 

Transport Security

p_w_picpath

 

Message Security

p_w_picpath

 

(一)Demo代碼

IDemoService.cs:

複製代碼

using System.ServiceModel;namespace WCFDemo
{    
    [ServiceContract(Name = "IDemoService")]    public interface IDemoService
    {
        [OperationContract]
        [FaultContract(typeof(DivideByZeroFault))] 
        int Divide(int numerator, int denominator);
    }
}

複製代碼

 

DemoService.cs:

複製代碼

using System;using System.ServiceModel;using System.ServiceModel.Activation;namespace WCFDemo
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    public class DemoService : IDemoService
    {        public int Divide(int numerator, int denominator)
        {            try
            {                return numerator / denominator;
            }            catch (DivideByZeroException ex)
            {
                DivideByZeroFault fault = new DivideByZeroFault();
                fault.Error = ex.Message;
                fault.Detail = "Denominator cannot be ZERO!";                throw new FaultException<DivideByZeroFault>(fault);
            }           
        }
    }
}

複製代碼

 

(二)創建證書

basicHttpBinding使用Message Security mode時,credential type只能爲Certificate(參見《WCF Security基本概念》

312317464879122

 

在服務器上創建服務器端證書。

p_w_picpath

 


屬性解析

-sr 指定的證書存儲區中的註冊表位置。

  • currentUser 指定註冊版存儲位置爲 HKEY_CURRENT_USER.

  • localMachine 指定註冊版存儲位置爲 HKEY_LOCAL_MACHINE.

 

-ss 指定證書存儲的位置。

 

-a 指定相關的算法,可以選擇 MD5 算法或者 SHA1算法

 

-n 指定證書的名稱。該名稱遵循X.500命名標準。簡單例子如 "CN=MyName" 格式,如果沒有指定/n開關,證書默認的名稱是"Joe's Software Emporium"。

 

-sky 證書鍵類型。可以設置爲 exchange 或者 signature。

 

-pe 證書可導出

 

-r Self-signed Certificate

 

證書創建成功,下面在證書控制單元查看證書的信息

 

p_w_picpath

p_w_picpath

 

選擇Certificates –> Add

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

 

需要給IIS運行WCF Service的Application Pool的帳號對這個證書私鑰的讀權限(參考《IIS ApplicationPoolIdentity》

 

p_w_picpath

 

否則會報出以下錯誤

 

p_w_picpath

 

 

將服務器端的證書導出,然後導入到客戶端。

 

從服務器導出證書:

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

 

將導出的證書複製到客戶端,然後導入:

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

p_w_picpath

 

用同樣的方法在客戶端創建DemoCertClient證書,然後導入到服務器。

 

客戶端(不要忘記給調用WCF Service的程序帳號賦予對私鑰的讀權限),客戶端保存DemoCertClient的證書加私鑰和DemoCertServer的證書(無私鑰)。

p_w_picpath

 

服務器端保存DemoCertServer的證書加私鑰和DemoCertClient的證書(無私鑰)。

p_w_picpath

 

(三)服務器端配置文件

Server web.config:

複製代碼

<?xml version="1.0"?> 
<configuration> 
    <system.web> 
      <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
      <bindings> 
        <basicHttpBinding> 
          <binding name="basicBinding"> 
            <security mode="Message"> 
              <message clientCredentialType="Certificate" /> 
            </security> 
          </binding> 
        </basicHttpBinding> 
      </bindings> 
      <services> 
        <service name="WCFDemo.DemoService" behaviorConfiguration="CustomBehavior"> 
          <endpoint address="DemoService" binding="basicHttpBinding" contract="WCFDemo.IDemoService" bindingConfiguration="basicBinding"> 
            <identity> 
              <dns value="DemoCertServer"/> 
            </identity> 
          </endpoint> 
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint> 
        </service> 
      </services> 
        <behaviors> 
            <serviceBehaviors> 
                <behavior name="CustomBehavior"> 
                    <serviceMetadata httpGetEnabled="true" /> 
                    <serviceDebug includeExceptionDetailInFaults="false" /> 
                    <serviceCredentials> 
                      <serviceCertificate findValue="DemoCertServer" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/> 
                      <clientCertificate> 
                        <authentication certificateValidationMode="None"/> 
                      </clientCertificate> 
                    </serviceCredentials> 
                </behavior> 
            </serviceBehaviors> 
        </behaviors> 
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
</configuration>

複製代碼

 

<dns value="DemoCertServer"/>應該使用Server證書的名字。

 

(四)客戶端配置文件

client app.config中如果沒有定義clientCertificate

<clientCertificate findValue="DemoCertClient" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/>

會有如下的異常:

p_w_picpath

 

client app.config中如果沒有定義serviceCertificate:

<serviceCertificate>
  <authentication certificateValidationMode="None"/>
  <defaultCertificate findValue="DemoCertServer" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/></serviceCertificate>

會有如下異常:

p_w_picpath

 

如果沒有對identy.dns定義

<identity> 
  <dns value="DemoCertServer"/> </identity>

會有如下錯誤(dns的值應爲服務器證書名稱)

p_w_picpath

 

client app.config:

複製代碼

<?xml version="1.0" encoding="utf-8" ?> <configuration> 
    <system.serviceModel> 
        <bindings> 
            <basicHttpBinding> 
                <binding name="BasicHttpBinding_IDemoService"> 
                    <security mode="Message"> 
                        <message clientCredentialType="Certificate" /> 
                    </security> 
                </binding> 
            </basicHttpBinding> 
        </bindings> 
        <client> 
          <endpoint address="http://169.254.14.147:8080/DemoService.svc/DemoService" 
              binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IDemoService" 
              contract="DemoServiceReference.IDemoService" name="BasicHttpBinding_IDemoService" 
              behaviorConfiguration="CustomBehavior" >             <identity> 
              <dns value="DemoCertServer"/> 
            </identity>           </endpoint> 
        </client> 
        <behaviors> 
          <endpointBehaviors>             <behavior name="CustomBehavior"> 
              <clientCredentials> 
                <!--客戶端證書--> 
                <clientCertificate findValue="DemoCertClient" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/> 
                <serviceCertificate> 
                  <authentication certificateValidationMode="None"/> 
                  <defaultCertificate findValue="DemoCertServer" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/> 
                </serviceCertificate> 
              </clientCredentials> 
            </behavior> 
          </endpointBehaviors> 
        </behaviors> 
    </system.serviceModel> </configuration>

複製代碼

 生面高亮部分如果沒有需要手動填加。

 

(五)運行程序,監聽Message

最後運行程序,調用WCF Service成功。

p_w_picpath

p_w_picpath

 

request:

複製代碼

<MessageLogTraceRecord> 
  <HttpRequest xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"> 
    <Method>POST</Method> 
    <QueryString></QueryString> 
    <WebHeaders> 
      <Connection>Keep-Alive</Connection> 
      <Content-Length>5679</Content-Length> 
      <Content-Type>text/xml; charset=utf-8</Content-Type> 
      <Accept-Encoding>gzip, deflate</Accept-Encoding> 
      <Expect>100-continue</Expect> 
      <Host>169.254.14.147:8080</Host> 
      <VsDebuggerCausalityData>uIDPo9Vi8e1+m5dBjpQNi0apJP0AAAAATyHJhOUUEkmuMAERj3wPbUFg0jBteBFLj/A/pVmLhYMACQAA</VsDebuggerCausalityData> 
      <SOAPAction>"http://tempuri.org/IDemoService/Divide"</SOAPAction> 
    </WebHeaders> 
  </HttpRequest> 
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> 
    <s:Header> 
      <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> 
        <u:Timestamp u:Id="uuid-c99aa3d8-badd-4da0-8f75-66a613cca7e6-1"> 
          <u:Created>2014-11-01T10:09:00.392Z</u:Created> 
          <u:Expires>2014-11-01T10:14:00.392Z</u:Expires> 
        </u:Timestamp> 
        <o:BinarySecurityToken> 
          <!-- Removed--> 
        </o:BinarySecurityToken> 
        <e:EncryptedKey Id="_0" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
          <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"> 
            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" xmlns="http://www.w3.org/2000/09/xmldsig#"></DigestMethod> 
          </e:EncryptionMethod> 
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> 
            <o:SecurityTokenReference> 
              <X509Data> 
                <X509IssuerSerial> 
                  <X509IssuerName>CN=DemoCertServer</X509IssuerName> 
                  <X509SerialNumber>-30526433464546109314442804636326321278</X509SerialNumber> 
                </X509IssuerSerial> 
              </X509Data> 
            </o:SecurityTokenReference> 
          </KeyInfo> 
          <e:CipherData> 
            <e:CipherValue>eCF+OqdyUWdJPIQdAX1yN1sUkMyKdxXPZvx1F5s/NuqEaGMR/kj0vCXok27J46fjN31K9VgrcqWcZn/lbiNzjGGinAI7NDTZJwDkHDCzJvgwG8zXun9OB7XxaRoJ2PnokbtkAcjIB1A2wXlulD8O1Zopf4UfTj6gSp+69eNYK+//6gIu+Udszo0D0TlM9GbQkdhZnu/+TwWOLYqpaNBO6p2bynxKl99Zf/3Ghclps++pan1umxCb1XIe6T4A/DbG6SXJ/uND0W9cOt1w5VyP54EclTjTCfEK9KD7n97Xjxu45a6nkU4+svBetBYm0hD/vCNyIS8kAs30UiOA0AQP+A==</e:CipherValue> 
          </e:CipherData> 
          <e:ReferenceList> 
            <e:DataReference URI="#_2"></e:DataReference> 
            <e:DataReference URI="#_3"></e:DataReference> 
          </e:ReferenceList> 
        </e:EncryptedKey> 
        <e:EncryptedData Id="_3" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
          <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod> 
          <e:CipherData> 
            <e:CipherValue>XvuuOuqInRdHz5TMd5laV2OWf+MeqyJmT9p2KBJd0KhZMv+MOTbUshxUvIrfMPgFQv7aVRDTB6BlQ9Dl9peHzpYd7rSGvt2GmcUOw/XmBEi12/z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NNAS1a1/KYdhCek5zPSJs6f0uaJ9fEnviIe5djVKFrZaQKCHaSgxXYU4cIx805ATbk0JZNX/D+Wwasz1x4BCIUv2Myol8QbqmRMOKXE0b1LI516pGUnq6Q5RJ3tA9nB+I17HEQFQGsheiS/ZXZEHE2MLKPaaDTu8V+PGbtB1Y/swtCz3qqrzmrgRI7Po0uh36VzMyxx9fF3QyAoUexbQWb9PEJQKfMIKBY30kDPKFob3MeQkVbouNydebFCCSW5vefr9g6Cmv4mRjmTwuS98KAHxlRwwqZ8WYxR5YtPg+vQvIbdBJTKd8A7n39a1/0Y3YXNWxC24hNGOT89hHjPtQqCC0iTgSdf7yepy7btlixd4t+SsAHi/2zKkNZVqWTOBZp10yy6JuC24fOybRp3ySwfZLpH2J9QZkmIptqXruPOX5Hwig9SWmMkB6NJUQHvNx1GHb2JMXw1M4uQ/NV4uqewqztPKAgz+puKPW3set2+9jP/e/eWrxeoA7SpmLcYTeW0xM84D6c1xnizTF89k9FzrqueYqKv+5ndWOhN4Fym5NPlbsMSInAxYzh+JOZjzA+ny0VIDjX3LeMyZjAJnzigzwmRCnHYLuX6/tk0YGzZptNyo5tXlv9L5NAqel4QgrUY2Zcm4uBa8AUBcdKwM2xJ8nXgj5ArqXzF3+gt3otlfrTr0lMEjRBRjHAivPYpkP8iMtrhLjRSo837PaRV/l5xf+l0vWmjqHK6WGgtkuW75VssKv/v/ej18dc52pndcPKyCS0DJrmE4CpXPShyEq11wT7xu0TEtmKp5sFIDQ7vB3w1A==</e:CipherValue> 
          </e:CipherData> 
        </e:EncryptedData> 
      </o:Security> 
      <To s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://win-ounm08eqe64.henry.huang:8080/DemoService.svc/DemoService</To> 
      <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IDemoService/Divide</Action> 
    </s:Header> 
    <s:Body u:Id="_1"> 
      <e:EncryptedData Id="_2" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
        <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod> 
        <e:CipherData> 
          <e:CipherValue>MW5NSJm9V6HE2u7Q5ZKMbZ0vn/T6CA/muPY0YvvV1F06Pq01NsCE5t0OovNYlvSAJtII/lB7y815CVQDqfvid1WFRNfDJvr5LKfw+HC6WF0qpyVHvgbjgXhMkW12kj9pa5nc6LzVJYi0VEm7+gcae/VA+OCyFu5Ch0GQM4eEFDk=</e:CipherValue> 
        </e:CipherData> 
      </e:EncryptedData> 
    </s:Body> 
  </s:Envelope> </MessageLogTraceRecord>

複製代碼

 

 

response:

複製代碼

<MessageLogTraceRecord> 
  <Addressing xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace"> 
    <Action>http://tempuri.org/IDemoService/DivideResponse</Action> 
  </Addressing> 
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> 
    <s:Header> 
      <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"> 
        <u:Timestamp u:Id="uuid-4537aa5c-6e49-467b-8f7c-0c1406bbdd4c-1"> 
          <u:Created>2014-11-01T10:09:01.290Z</u:Created> 
          <u:Expires>2014-11-01T10:14:01.290Z</u:Expires> 
        </u:Timestamp> 
        <e:EncryptedKey Id="_0" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
          <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"> 
            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" xmlns="http://www.w3.org/2000/09/xmldsig#"></DigestMethod> 
          </e:EncryptionMethod> 
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#"> 
            <o:SecurityTokenReference> 
              <X509Data> 
                <X509IssuerSerial> 
                  <X509IssuerName>CN=DemoCertClient</X509IssuerName> 
                  <X509SerialNumber>44895421441865058621951489303975545421</X509SerialNumber> 
                </X509IssuerSerial> 
              </X509Data> 
            </o:SecurityTokenReference> 
          </KeyInfo> 
          <e:CipherData> 
            <e:CipherValue>hbA9quGesDhaEmybXgczWaEC//Pfo9rn1o8nM1JDw1oDVZzfiOx+DHnnhyzKi8SqWqIyjZ0WGcJ4hr1gnxXj4XEW1nBhSIu1EWaVP/ooKFE9DgHwXjT3bSpG/zcoWDbCEA5dIGmU0mcDtunOStPYi4mTRueI6JABmcC2BdpNL9Y002CYLwlPHjwsfTD1+frewRvO6Czmtjjk6/3cc7RaN9GLP1tDNYManlpG7cvZWYn89l/N60ra16w+Ktr/EbjWol2HAj67jG7R02x/Gk7mze6dwMzp2Ll6UHc4EqYMRdGF3T6lPilGkkvtfWuQPlSvZq8osK2/ornu0taeg05j5w==</e:CipherValue> 
          </e:CipherData> 
          <e:ReferenceList> 
            <e:DataReference URI="#_2"></e:DataReference> 
            <e:DataReference URI="#_3"></e:DataReference> 
          </e:ReferenceList> 
        </e:EncryptedKey> 
        <e:EncryptedData Id="_3" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
          <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod> 
          <e:CipherData> 
            <e:CipherValue>F6LRB7VUwjAFZAaVmh8PLzC69H2qBRI/Gxpr3ej8oBi4spHKfJV7VF9eqKB0L+7KkD5fAiDO+J0iDmvLAcAeEm0ec0qHfoe5ln2m6YL7V67u/AkUu1Pawp6Kw68bzPxibzzLr1bJ5pNtUHNUaa2LfaEVR6dMZPv/X/pmPwl2qzlts4dVm+sZ5LHHAqHBAct1x1/mfQr5e+L0Z6m/aU5ti8zc5rxwASG7nf2fyOKcdFaqevDQ/gV8hZjXcNzw/l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NOHIhX6XBNDAnUnNdIz6Qds7dVgw70Q+hH9If3cVJauuxTfxW2jr5UJ5K4IIZDmPdV8XM8mg03XrCUlpyDMNNyhrC9D8GI7MKGzZI2YvshDHJxXD+NBWnWjYIOoHnZyZ45DXN3ONQiHvIWmKNrWdQMGH8FOtwjKCV98WoFSCBQeGJbJFLuRtUVR8ojJlYEkQfWsHsVDAUuFjrzETHfM45WbMH48wwuoca4/6lV8iYhCHn9WnAbFkM6bmEpBh6u+Cy8wZIhnoHvd2HfJmiRQWbUmIZi6FwpS6krF+prcEBJIPI4FFBe8uk0r3l7UQ80DRaTzji00R7bCopAfcFcXgKpFrL0wMjrUi4VNudvo6Er8rWQBDo4Bl0pu682HNQcwvhqApYcBnvx/GpseQIXSI345eqewd/JeK8Ss0Uzl58adAKdq5aNaan+LY26x6k+kSiP2rHAiJKG5F8KyP/lAdCiS75HDf7JMNPf1GNYIcEXlJ3itKTmn8jOWvlsdqhYNTqhdg7zR+Bf/eqnZF6+F1aRg/SAxWdPjNRk4YXk0vhmqkBWhS++li842o6bpuh2mZBjSjOVbUPkVQBSN6rxG5NHCU7U1bLGkBtuyy+s5nbLy35Lk9BW7i9othC8HKOD2U5jWW3PIWPD+/dhuLNM/OqNrjNdTH+kAZbJ9G5+2/jw9V/Iz52RjGo0c4=</e:CipherValue> 
          </e:CipherData> 
        </e:EncryptedData> 
      </o:Security> 
    </s:Header> 
    <s:Body u:Id="_1"> 
      <e:EncryptedData Id="_2" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:e="http://www.w3.org/2001/04/xmlenc#"> 
        <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"></e:EncryptionMethod> 
        <e:CipherData> 
          <e:CipherValue>XHR3ci6ob5bXSsEzeL+UE3RJLRHkvk7oLBoHF8zkGuPH/oK7rqq6Pu4GWyPH0rOt33oNoociNCG53KcvtcJWygnoy8h47L8nuYka95fOBx7W4jlYlU5Zad0LjiydAAVlu3zi7LiQ6nH4osrLD1I80Q==</e:CipherValue> 
        </e:CipherData> 
      </e:EncryptedData> 
    </s:Body> 
  </s:Envelope> </MessageLogTraceRecord>

複製代碼

 

可以看到request和response的信息都已經被加密了。

 

(六)總結

basicHttpBinding的Message Security Mode必須使用Certificate credential type。

 

它的原理是服務器端和客戶端各自有自己創建的證書:

(1)客戶端向服務器端發送請求時,客戶端使用服務器端的公鑰進行加密,服務器端使用自己的私鑰解密。

(2)服務器向客戶端響應時,使用客戶端的公鑰進行加密,客戶端使用自己的私鑰解密。

 

另外注意服務器端的Application Pool的運行帳號需要對服務器證書的私鑰有讀取權限;客戶端運行調用WCF程序的帳號需要對客戶端證書的私鑰有讀取權限。

 

說明 certificateValidationMode共有以下五種模式。

None: 未執行任何證書驗證。

PeerTrust:如果證書位於被信任的人的存儲區中,則有效。

ChainTrust:如果證書鏈在受信任的根存儲區生成證書頒發機構,則證書有效。

PeerOrChainTrust:如果證書位於被信任的人的存儲區或證書鏈在受信任的根存儲區生成證書頒發機構,則證書有效。

Custom:用戶必須插入自定義 X509CertificateValidator 以驗證證書。

因爲本文目的在於演示,所以certificateValidationMode都使用的是None,在生產環境中,應該使用有效的證書,並使用ChainTrust。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章