先来看一个最简单的加法运算通过wcf来实现。
namespace Contract
{
[ServiceContract]
public interface IService
{
[OperationContract]
int add(int a, int b);
}
}
public class Service:Contract.IService
{
IService 成员
}
服务端的配置文件如下:{
[ServiceContract]
public interface IService
{
[OperationContract]
int add(int a, int b);
}
}
public class Service:Contract.IService
{
IService 成员
}
<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,至此我们已经建立了一个wcf的加法运算。下一步我将讲解如何为建立好的应用程序加入安全机制。<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>
我们可以通过在服务器端配置证书来加密和解密传输数据来保证数据的完整性和机密性。我们来为服务器配置证书。
由于我在这里只做Demo演示,证书可以通过markcert.exe命令来完成,如果作为企业应用的话,请到CA申请受信任的证书。证书的介绍和制作方法在我以前写过的Blogs上可以看到。
在WCF中可以通过将上述步骤中生成的证书以配置文件的方式添加到WCF的配置文件中,就可以实现服务器的安全,以及数据在传输中的加密和解密了。
服务器端配置文件添加如下内容
<serviceCredentials>
<clientCertificate>
<authentication certificateValidationMode="None" />
</clientCertificate>
<serviceCertificate findValue="Guotai.WeighingSystem.ServerCA" storeLocation="CurrentUser" x509FindType="FindBySubjectName" />
</serviceCredentials>
同样在客户端添加以下节点:<clientCertificate>
<authentication certificateValidationMode="None" />
</clientCertificate>
<serviceCertificate findValue="Guotai.WeighingSystem.ServerCA" storeLocation="CurrentUser" x509FindType="FindBySubjectName" />
</serviceCredentials>
<endpointBehaviors>
<behavior name="NewBehavior">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
请注意serviceCertificate节点,由于我们建立的证书只是用来测试用,不受信任的,因此将证书验证模式设为:None,否则程序运行时报错。<behavior name="NewBehavior">
<clientCredentials>
<serviceCertificate>
<authentication certificateValidationMode="None" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
OK,现在我们已经实现了数据完整性和数据机密性。
有兴趣的朋友,可以用Service Trace Viewer这个工具来将WCF在数据传输中所记录的日志文件打开,如果WCF服务配置了以上的安全措施,那么在这个工具中可以看到WCF传输过程中的数据都是以密文的方式传输的。Enjoy..
在下面两节中将介绍认证和授权。