WCF服務(wù)端安全實現(xiàn)技巧剖析
WCF作為一款功能強大的開發(fā)工具給我們帶來了非常不一樣的使用體驗。它的安全性方面是非常重要的。在這里我們將會為大家詳細介紹一下WCF服務(wù)端安全的相關(guān)應(yīng)用知識,方便大家理解這方面的內(nèi)容。
先來看一個最簡單的加法運算通過WCF來實現(xiàn)。
- 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)建立了一個WCF的加法運算。下一步我將講解如何為建立好的應(yīng)用程序加入安全機制。我們可以通過在服務(wù)器端配置證書來加密和解密傳輸數(shù)據(jù)來保證數(shù)據(jù)的完整性和機密性。我們來為服務(wù)器配置證書。由于我在這里只做Demo演示,證書可以通過markcert.exe命令來完成,如果作為企業(yè)應(yīng)用的話,請到CA申請受信任的證書。證書的介紹和制作方法在我以前寫過的Blogs上可以看到。在WCF中可以通過將上述步驟中生成的證書以配置文件的方式添加到WCF的配置文件中,就可以實現(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é)點:
- < endpointBehaviors>
- < behavior name="NewBehavior">
- < clientCredentials>
- < serviceCertificate>
- < authentication certificateValidationMode="None" />
- < /serviceCertificate>
- < /clientCredentials>
- < /behavior>
- < /endpointBehaviors>
請注意serviceCertificate節(jié)點,由于我們建立的證書只是用來測試用,不受信任的,因此將證書驗證模式設(shè)為:None,否則程序運行時報錯。OK,現(xiàn)在我們已經(jīng)實現(xiàn)了數(shù)據(jù)完整性和數(shù)據(jù)機密性。有興趣的朋友,可以用Service Trace Viewer這個工具來將WCF在數(shù)據(jù)傳輸中所記錄的日志文件打開,如果WCF服務(wù)端安全配置了以上的安全措施,那么在這個工具中可以看到WCF傳輸過程中的數(shù)據(jù)都是以密文的方式傳輸?shù)摹?/p>
【編輯推薦】