WCF服務(wù)端安全實(shí)現(xiàn)技巧剖析
WCF作為一款功能強(qiáng)大的開(kāi)發(fā)工具給我們帶來(lái)了非常不一樣的使用體驗(yàn)。它的安全性方面是非常重要的。在這里我們將會(huì)為大家詳細(xì)介紹一下WCF服務(wù)端安全的相關(guān)應(yīng)用知識(shí),方便大家理解這方面的內(nèi)容。
先來(lái)看一個(gè)最簡(jiǎn)單的加法運(yùn)算通過(guò)WCF來(lái)實(shí)現(xiàn)?!?/p>
- namespace Contract
- {
- [ServiceContract]
- public interface IService
- {
- [OperationContract]
- int add(int a, int b);
- }
- }
- public class Service:Contract.IService
- {
- IService 成員#region IService 成員
- public int add(int a, int b)
- {
- return a + b;
- }
- #endregion
- }
WCF服務(wù)端安全的配置文件如下:
- < system.serviceModel>
- < behaviors>
- < serviceBehaviors>
- < behavior name="ServiceBehavior">
- < serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
- < /serviceBehaviors>
- < /behaviors>
- < services>
- < service behaviorConfiguration="ServiceBehavior"
name="Service.Service">- < endpoint binding="wsHttpBinding" contract="Contract.IService" />
- < host>
- < baseAddresses>
- < add baseAddress="http://localhost:123/service" />
- < /baseAddresses>
- < /host>
- < /service>
- < /services>
- < /system.serviceModel>
OK,至此我們已經(jīng)建立了一個(gè)WCF的加法運(yùn)算。下一步我將講解如何為建立好的應(yīng)用程序加入安全機(jī)制。我們可以通過(guò)在服務(wù)器端配置證書來(lái)加密和解密傳輸數(shù)據(jù)來(lái)保證數(shù)據(jù)的完整性和機(jī)密性。我們來(lái)為服務(wù)器配置證書。由于我在這里只做Demo演示,證書可以通過(guò)markcert.exe命令來(lái)完成,如果作為企業(yè)應(yīng)用的話,請(qǐng)到CA申請(qǐng)受信任的證書。證書的介紹和制作方法在我以前寫過(guò)的Blogs上可以看到。在WCF中可以通過(guò)將上述步驟中生成的證書以配置文件的方式添加到WCF的配置文件中,就可以實(shí)現(xiàn)WCF服務(wù)端安全,以及數(shù)據(jù)在傳輸中的加密和解密了。服務(wù)器端配置文件添加如下內(nèi)容
- < serviceCredentials>
- < clientCertificate>
- < authentication certificateValidationMode="None" />
- < /clientCertificate>
- < serviceCertificate findValue="Guotai.WeighingSystem.ServerCA"
storeLocation="CurrentUser" x509FindType="FindBySubjectName" />- < /serviceCredentials>
同樣在客戶端添加以下節(jié)點(diǎn):
- < endpointBehaviors>
- < behavior name="NewBehavior">
- < clientCredentials>
- < serviceCertificate>
- < authentication certificateValidationMode="None" />
- < /serviceCertificate>
- < /clientCredentials>
- < /behavior>
- < /endpointBehaviors>
請(qǐng)注意serviceCertificate節(jié)點(diǎn),由于我們建立的證書只是用來(lái)測(cè)試用,不受信任的,因此將證書驗(yàn)證模式設(shè)為:None,否則程序運(yùn)行時(shí)報(bào)錯(cuò)。OK,現(xiàn)在我們已經(jīng)實(shí)現(xiàn)了數(shù)據(jù)完整性和數(shù)據(jù)機(jī)密性。有興趣的朋友,可以用Service Trace Viewer這個(gè)工具來(lái)將WCF在數(shù)據(jù)傳輸中所記錄的日志文件打開(kāi),如果WCF服務(wù)端安全配置了以上的安全措施,那么在這個(gè)工具中可以看到WCF傳輸過(guò)程中的數(shù)據(jù)都是以密文的方式傳輸?shù)摹?/p>
【編輯推薦】