基于消息队列的消息安全性
MessageSecurity 示例 演示了如何实现对客户端使用具有 X.509v3 证书身份验证 WS-Security 的应用程序,并要求使用服务器的 X.509v3 证书通过 MSMQ 进行身份验证。 有时更需要消息安全性,以确保 MSMQ 存储中的消息保持加密状态,并且应用程序可以对其自己的消息进行身份验证。
该示例基于事务处理 MSMQ 绑定示例。 消息经过加密和签名。
设置、生成和运行示例
确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。
如果先运行服务,则它将检查以确保队列存在。 如果队列不存在,服务将创建一个队列。 可以先运行服务来创建队列,也可以通过 MSMQ 队列管理器创建一个队列。 按照以下步骤在 Windows 2008 中创建队列。
在 Visual Studio 2012 中打开服务器管理器。
展开“功能”选项卡。
右键单击 专用消息队列,然后选择 “新建”,专用队列。
选中“事务性”框。
输入
ServiceModelSamplesTransacted
作为新队列的名称。
若要生成解决方案的 C# 或 Visual Basic 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。
在同一计算机上运行示例
确保路径包含包含 Makecert.exe 和 FindPrivateKey.exe的文件夹。
从示例安装文件夹运行 Setup.bat。 这会安装运行示例所需的所有证书。
注意
完成示例后,请确保通过运行 Cleanup.bat 来删除证书。 其他安全示例使用相同的证书。
从 \service\bin 启动 Service.exe。
从 \client\bin 启动 Client.exe。 客户端活动显示在客户端控制台应用程序中。
跨计算机运行示例
将 Setup.bat、Cleanup.bat和 ImportClientCert.bat 文件复制到服务计算机。
在客户端计算机上为客户端二进制文件创建目录。
将客户端程序文件复制到客户端计算机上的客户端目录。 此外,将 Setup.bat、Cleanup.bat和 ImportServiceCert.bat 文件复制到客户端。
在服务器上,运行
setup.bat service
。 使用service
参数运行setup.bat
,则使用计算机的完全限定域名创建一个服务证书,并将此服务证书导出到名为 Service.cer 的文件中。编辑服务的 Service.exe.config 以反映新的证书名称(在 <serviceCertificate> 的
findValue
属性中),该名称与计算机的完全限定域名相同。将Service.cer文件从服务目录复制到客户端计算机上的客户端目录。
在客户端上运行
setup.bat client
。 使用client
参数运行setup.bat
将创建名为 client.com 的客户端证书,并将客户端证书导出到名为Client.cer的文件。在客户端计算机上的 Client.exe.config 文件中,更改终结点的地址值以匹配服务的新地址。 通过用服务器的完全限定域名替换 localhost 来执行此操作。 还必须更改服务的证书名称,使其与服务计算机的完全限定域名相同(在
findValue
下的defaultCertificate
的serviceCertificate
元素的clientCredentials
属性中)。将Client.cer文件从客户端目录复制到服务器上的服务目录。
在客户端上运行
ImportServiceCert.bat
。 这会将服务证书从 Service.cer 文件导入 CurrentUser - TrustedPeople 存储中。在服务器上,运行
ImportClientCert.bat
,这会将客户端证书从 Client.cer 文件导入 LocalMachine - TrustedPeople 存储。在服务计算机上,从命令提示符启动 Service.exe。
在客户端计算机上,从命令提示符启动 Client.exe。 如果客户端和服务无法通信,请参阅 WCF 示例 故障排除提示。
运行示例后进行清理
运行完示例后,在示例文件夹中运行 Cleanup.bat。
注意
在跨计算机运行此示例时,此脚本不会删除客户端上的服务证书。 如果您运行了在不同计算机上使用证书的 Windows Communication Foundation (WCF) 示例,请确保清除已安装在当前用户 - TrustedPeople 存储库中的服务证书。 为此,请使用以下命令:
certmgr -del -r CurrentUser -s TrustedPeople -c -n <Fully Qualified Server Machine Name>
例如:certmgr -del -r CurrentUser -s TrustedPeople -c -n server1.contoso.com
。
要求
此示例要求安装并运行 MSMQ。
演示
客户端使用服务的公钥加密消息,并使用自己的证书对消息进行签名。 从队列中读取消息的服务使用其受信任人的存储区中的证书对客户端证书进行身份验证。 然后,它会解密消息并将消息调度到服务操作。
由于 Windows Communication Foundation (WCF) 消息作为 MSMQ 消息正文中的有效负载进行传输,因此正文在 MSMQ 存储中仍保持加密状态。 这将保护消息免于不当披露。 请注意,MSMQ 本身不知道它携带的消息是否已加密。
此示例演示了如何在消息级别与 MSMQ 一起使用相互身份验证。 证书是在带外交换的。 通常情况是,对于队列应用程序来说,服务和客户端不必同时启动并运行。
描述
示例客户端和服务代码与 Transacted MSMQ 绑定 示例相同,但有一个差异。 操作协定使用保护级别进行批注,这表明必须对消息进行签名和加密。
// Define a service contract.
[ServiceContract(Namespace="http://Microsoft.ServiceModel.Samples")]
public interface IOrderProcessor
{
[OperationContract(IsOneWay = true, ProtectionLevel=ProtectionLevel.EncryptAndSign)]
void SubmitPurchaseOrder(PurchaseOrder po);
}
为了确保使用所需的令牌保护消息以标识服务和客户端,App.config 包含凭据信息。
客户端配置指定要对服务进行身份验证的服务证书。 它使用其本地计算机存储区作为受信任的存储区,以依赖服务的有效性。 它还指定随消息一起附加的客户端证书,以便对客户端进行服务身份验证。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesMessageSecurity"
binding="netMsmqBinding"
bindingConfiguration="messageSecurityBinding"
contract="Microsoft.ServiceModel.Samples.IOrderProcessor"
behaviorConfiguration="ClientCertificateBehavior" />
</client>
<bindings>
<netMsmqBinding>
<binding name="messageSecurityBinding">
<security mode="Message">
<message clientCredentialType="Certificate"/>
</security>
</binding>
</netMsmqBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="ClientCertificateBehavior">
<!--
The clientCredentials behavior allows one to define a certificate to present to a service.
A certificate is used by a client to authenticate itself to the service and provide message integrity.
This configuration references the "client.com" certificate installed during the setup instructions.
-->
<clientCredentials>
<clientCertificate findValue="client.com" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName" />
<serviceCertificate>
<defaultCertificate findValue="localhost" storeLocation="CurrentUser" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
<!--
Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
is in the user's Trusted People store, then it is trusted without performing a
validation of the certificate's issuer chain. This setting is used here for convenience so that the
sample can be run without having to have certificates issued by a certification authority (CA).
This setting is less secure than the default, ChainTrust. The security implications of this
setting should be carefully considered before using PeerOrChainTrust in production code.
-->
<authentication certificateValidationMode="PeerOrChainTrust" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
请注意,安全模式设置为 Message,ClientCredentialType 设置为 Certificate。
服务配置包括一种服务行为,用于指定客户端对服务进行身份验证时使用的服务的凭据。 服务器证书的主题名称是在 <serviceCredentials>的 findValue
属性中指定的。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<!-- Use appSetting to configure MSMQ queue name. -->
<add key="queueName" value=".\private$\ServiceModelSamplesMessageSecurity" />
</appSettings>
<system.serviceModel>
<services>
<service
name="Microsoft.ServiceModel.Samples.OrderProcessorService"
behaviorConfiguration="PurchaseOrderServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
</baseAddresses>
</host>
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesMessageSecurity"
binding="netMsmqBinding"
bindingConfiguration="messageSecurityBinding"
contract="Microsoft.ServiceModel.Samples.IOrderProcessor" />
<!-- The mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex. -->
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netMsmqBinding>
<binding name="messageSecurityBinding">
<security mode="Message">
<message clientCredentialType="Certificate" />
</security>
</binding>
</netMsmqBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="PurchaseOrderServiceBehavior">
<serviceMetadata httpGetEnabled="True"/>
<!--
The serviceCredentials behavior allows one to define a service certificate.
A service certificate is used by the service to authenticate itself to its clients and to provide message protection.
This configuration references the "localhost" certificate installed during the setup instructions.
-->
<serviceCredentials>
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
<clientCertificate>
<certificate findValue="client.com" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName"/>
<!--
Setting the certificateValidationMode to PeerOrChainTrust means that if the certificate
is in the user's Trusted People store, then it is trusted without performing a
validation of the certificate's issuer chain. This setting is used here for convenience so that the
sample can be run without having to have certificates issued by a certification authority (CA).
This setting is less secure than the default, ChainTrust. The security implications of this
setting should be carefully considered before using PeerOrChainTrust in production code.
-->
<authentication certificateValidationMode="PeerOrChainTrust" />
</clientCertificate>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
此示例演示如何使用配置控制身份验证,以及如何从安全上下文中获取调用方标识,如以下示例代码所示:
// Service class which implements the service contract.
// Added code to write output to the console window.
public class OrderProcessorService : IOrderProcessor
{
private string GetCallerIdentity()
{
// The client certificate is not mapped to a Windows identity by default.
// ServiceSecurityContext.PrimaryIdentity is populated based on the information
// in the certificate that the client used to authenticate itself to the service.
return ServiceSecurityContext.Current.PrimaryIdentity.Name;
}
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void SubmitPurchaseOrder(PurchaseOrder po)
{
Console.WriteLine("Client's Identity {0} ", GetCallerIdentity());
Orders.Add(po);
Console.WriteLine("Processing {0} ", po);
}
//…
}
运行时,服务代码会显示客户端标识。 下面是服务代码的示例输出:
The service is ready.
Press <ENTER> to terminate service.
Client's Identity CN=client.com; ECA6629A3C695D01832D77EEE836E04891DE9D3C
Processing Purchase Order: 6536e097-da96-4773-9da3-77bab4345b5d
Customer: somecustomer.com
OrderDetails
Order LineItem: 54 of Blue Widget @unit price: $29.99
Order LineItem: 890 of Red Widget @unit price: $45.89
Total cost of this order: $42461.56
Order status: Pending
评论
创建客户端证书。
批处理文件中的以下行将创建客户端证书。 指定的客户名称用于所创建的证书的主题名称。 证书存储在
My
存储位置下的CurrentUser
存储区中。echo ************ echo making client cert echo ************ makecert.exe -sr CurrentUser -ss MY -a sha1 -n CN=%CLIENT_NAME% -sky exchange -pe
将客户端证书安装到服务器的受信任证书存储中。
批处理文件中的以下行将客户端证书复制到服务器的 TrustedPeople 存储中,以便服务器可以做出相关的信任或无信任决策。 要使在 TrustedPeople 存储中安装的证书由 Windows Communication Foundation (WCF) 服务信任,必须将客户端证书验证模式设置为
PeerOrChainTrust
或PeerTrust
值。 请参阅以前的服务配置示例,了解如何使用配置文件完成此操作。echo ************ echo copying client cert to server's LocalMachine store echo ************ certmgr.exe -add -r CurrentUser -s My -c -n %CLIENT_NAME% -r LocalMachine -s TrustedPeople
创建服务器证书。
Setup.bat 批处理文件中的以下行创建要使用的服务器证书:
echo ************ echo Server cert setup starting echo %SERVER_NAME% echo ************ echo making server cert echo ************ makecert.exe -sr LocalMachine -ss MY -a sha1 -n CN=%SERVER_NAME% -sky exchange -pe
%SERVER_NAME% 变量指定服务器名称。 证书存储在 LocalMachine 存储中。 如果使用服务参数(如
setup.bat service
)运行安装程序批处理文件,则 %SERVER_NAME% 包含计算机的完全限定域名。 否则,它默认为 localhost。将服务器证书安装到客户端的受信任证书存储中。
以下行将服务器证书复制到客户端的受信任人员库中。 此步骤是必需的,因为 Makecert.exe 生成的证书不受客户端系统隐式信任。 如果已有一个证书,该证书已植根于客户端受信任的根证书(例如Microsoft颁发的证书),则不需要使用服务器证书填充客户端证书存储区。
certmgr.exe -add -r LocalMachine -s My -c -n %SERVER_NAME% -r CurrentUser -s TrustedPeople
注意
如果你使用的是非美国Microsoft Windows 英语版,必须编辑 Setup.bat 文件,并将“NT AUTHORITY\NETWORK SERVICE”帐户名称替换为区域等效名称。