WCF basicHttpBinding之Message Security Mode

原创地址:http://www.cnblogs.com/jfzhu/p/4067873.html                                                                  

转载请注明出处

 

前面的文章《WCF Security基本概念》介绍了WCF的security mode,简单说Transport是transport级别上的加密,Message是message级别上的加密,参见下图:

 

Transport Security

image

 

Message Security

image

 

(一)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

 

在服务器上创建服务器端证书。

image

 


属性解析

-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

 

证书创建成功,下面在证书控制单元查看证书的信息

 

image

image

 

选择Certificates –> Add

image

image

image

image

image

 

需要给IIS运行WCF Service的Application Pool的帐号对这个证书私钥的读权限(参考《IIS ApplicationPoolIdentity》

 

image

 

否则会报出以下错误

 

image

 

 

将服务器端的证书导出,然后导入到客户端。

 

从服务器导出证书:

image

image

image

image

image

image

image

 

将导出的证书复制到客户端,然后导入:

image

image

image

image

image

image

image

 

用同样的方法在客户端创建DemoCertClient证书,然后导入到服务器。

 

客户端(不要忘记给调用WCF Service的程序帐号赋予对私钥的读权限),客户端保存DemoCertClient的证书加私钥和DemoCertServer的证书(无私钥)。

image

 

服务器端保存DemoCertServer的证书加私钥和DemoCertClient的证书(无私钥)。

image

 

(三)服务器端配置文件

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"/>

会有如下的异常:

image

 

client app.config中如果没有定义serviceCertificate:

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

会有如下异常:

image

 

如果没有对identy.dns定义

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

会有如下错误(dns的值应为服务器证书名称)

image

 

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成功。

image

image

 

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/zjGkQwGch6LH2E2SzGnqarQlu+xV587not/0PJvxjy+oV1e/magOuL8F9BRF4bHkknUH1PgENpRmM+jwCM5mjhne6RmBflAu81PqtBxGDqYJC2qXmvhNGRghvGiQyRuIMUpWqNl9yX1MlfKucN4JmfMfNvxk85cFQq5g3O/DQwhdwY3AaHQKBv4/3oNacp9r2mYRI5OEUi+6rE9b7Frkurve7hUvLeNs1SdTbzvDQoPxPpBu8oYXg9eABLC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VbouNydebFCCSW5vefr9g6Cmv4mRjmTwuS98KAHxlRwwqZ8WYxR5YtPg+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/l8zi3lEH+yf7ALxRYXQyxj8SsGVza+mV0Nbb603Dx5QzxcrEMtjE9IO2q7jk8wjQeothLryXNlDN636l3L+k6rzd2IalVhoXqTZIi+7aQU3e6K1ljKIKJfxC/+QwAdTdsrsXtgiiDRFaAQzqe2PsnlL8hjU1jedKCwEYILgGpKp/jB9Oyz+3qU7gaq+tZp4kralmVD/2Brehzjcu79UjSmpVKn7Ul36z7xMoPcAEqDZxzyUCp/jcA63g81LML3eW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EpBh6u+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。

 

 

 

posted @ 2014-11-01 22:21  AI观星台  阅读(9916)  评论(1编辑  收藏  举报