IBM®
跳转到主要内容
    中国 [选择]    使用条款
 
 
Select a scope: Search for:    
    首页    产品    服务与解决方案     支持与下载    个性化服务    
跳转到主要内容

developerWorks 中国  >  WebSphere  >

使用 WS-Security 在 WebSphere ESB Gateway 和 Microsoft .NET WCF 之间设置互操作性

developerWorks
文档选项

未显示需要 JavaScript 的文档选项

英文原文

英文原文


级别: 中级

Andrew J. Howes, 软件开发人员,WebSphere ESB 系统验证测试团队, IBM

2009 年 10 月 12 日

本文讲解如何设置 Microsoft .NET Windows Communication Foundation (WCF) Web 服务和客户机以操作 WebSphere ESB Service Gateway。WebSphere ESB V6.2 允许把 Service Gateway 配置为许多客户机和服务之间的中介,从而支持在这些不同的事务的头部或数据上执行一组共同的操作。WebSphere ESB 还允许应用 WS-Transaction 和 WS-Security 等 Web 服务策略集来控制导出和导入。

简介

IBM® WebSphere® Enterprise Service Bus V6.2(后面称为 WebSphere ESB)允许构造 Service Gateway 作为许多客户机和服务之间的中介,从而支持在这些不同的事务的头部或数据上执行一组共同的操作。另外,可以对 WebSphere ESB 导出和导入应用策略集,从而确保对消息应用标准的 Web 服务质量头部。本文中的示例涉及一个 Microsoft® .NET Windows® Communication Foundation (WCF) 客户机和服务,它使用 WebSphere ESB Service Gateway 作为中介。在这个场景中,客户机与 WebSphere ESB 服务的交互会应用 WS-Security 服务质量。使用 SSL 保护 WebSphere ESB 到 .NET WCF 服务的接口:

Microsoft .NET 客户机 => WS-Security => WebSphere ESB Gateway => SSL => .NET 服务。设置这个示例需要:

  • Microsoft Windows® Vista Business
  • Microsoft Visual Studio 2008 Professional Edition
  • WebSphere Enterprise Service Bus 6.2

启用 IIS

创建的 Web 服务将驻留在 Windows Internet Information Services Manager (IIS) 中,在使用 IIS 之前必须启用 IIS:

  1. 在 Vista 系统上,选择 Windows Start => Control Panel。
  2. 选择 Programs and Features。
  3. 在右边面板中,单击 Turn Windows features on or off。
  4. Windows features 对话框打开。选中 Internet Information Services 复选框。
  5. 双击 Web Management Tools,双击 IIS 6 Management Compatibility,然后选中 IIS 6 Metabase and IIS 6 Configuration Compatibility 复选框。
  6. 双击 World Wide Web Services,双击 Application Development Features,然后选中 ASP.NET 复选框。
  7. 单击 OK。

创建 WCF Web 服务

  1. 选择 Windows Start => All Programs => Microsoft Visual Studio 2008 => Microsoft Visual Studio 2008。
  2. 选择 File => New => Web site。
  3. 选择 WCF service template with Location => HTTP, URL => 与 http://myhost/mywcfservice 相似的文本,Language => Visual C#。单击 OK。

WCF 服务有四个需要开发或配置的主要组件:

  • Service.svc
  • IService.cs
  • Service.cs
  • Web.config

Service.svc

这是服务的实际端点 —— 将使用 http://myhost/mywcfervice/Service.svc 这样的 URL 访问这个服务。这个文件本身很简单,主要定义服务代码的位置:

<%@ ServiceHost Language="C#" Debug="true" Service="Service" 
        CodeBehind="~/App_Code/Service.cs" %>

IService.cs

WCF 服务的 IService.cs 文件包含服务使用的类的接口。下面的示例定义一个方法(LoanApplicationRequest)和类将使用的对象(Customer、Loan 等等):

using ...

[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IService
{
    [OperationContract]
    LoanApproval LoanApplicationRequest(LoanRequest request);
}

[DataContract]
// Customer Business Object
public class Customer
{
    [DataMember]
    public string FirstName;
    [DataMember]
    public string LastName;
    [DataMember]
    public string HouseNumber;
    [DataMember]
    public string PostCode;
    [DataMember]
    public DateTime DateOfBirth;
    [DataMember]
    public int CreditRating;
}
[DataContract]
// Loan Business Object
public class Loan
{
    [DataMember]
    public decimal Amount;
    [DataMember]
    public TimeSpan Duration;
    [DataMember]
    public DateTime StartDate;
    [DataMember]
    public decimal InterestRate;
}
[DataContract]
// LoanRequest Business Object
public class LoanRequest
{
    [DataMember]
    public Customer CustomerInformation;
    [DataMember]
    public Loan LoanInformation;

}
[DataContract]
// LoanApproval Business Object
public class LoanApproval
{
    [DataMember]
    public bool Approved;
    [DataMember]
    public string Comment;
    [DataMember]
    public string AccountNumber;
    [DataMember]
    public Customer CustomerInformation;
    [DataMember]
    public Loan LoanInformation;
}
[DataContract]
// LoanException Business Object
public class LoanException
{
    [DataMember]
    public string Message;
}

OperationContract 定义类中的每个方法,DataContract 定义类使用的每个对象。

Service.cs

服务代码的主要部分在 Service.cs 文件中,这个文件使用 IService.cs 文件中定义的接口,提供方法的实现。这个示例处理输入的 LoanRequest 对象,填充并返回一个 LoanApproval 对象:

using ...

[WebService(Namespace = "http://mywcf.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//
public class Service : IService
{

    /*
     * LoanApplicationRequest method
     * Used to check the incoming request data and decide if the loan
     * can be approved.
     * In:  LoanRequest
     * Returns: LoanApproval
     */
    [WebMethod]
 
    public LoanApproval LoanApplicationRequest(LoanRequest request)
    {

        LoanApproval response = new LoanApproval();

        Customer customer = request.CustomerInformation;

        Loan loan = request.LoanInformation;

        bool approved = false;
 
        int creditRating = customer.CreditRating;

        decimal loanAmount = loan.Amount;
        decimal tenK = 10000.0M;
        decimal fiveK = 5000.0M;

        if (loanAmount > tenK)
        {
	   approved = false;
        }
        if (creditRating > 7)
        {
            approved = true;
        }
        else if (creditRating > 5 && loanAmount <= fiveK)
        {
             approved = true;
        }
        response.Approved = approved;
        if (approved)
        {
             Random rnum = new Random();
             int accInt = 8 * rnum.Next(1000000);
             string accNo = accInt.ToString();
             response.AccountNumber = accNo;
             response.Comment = "Request Approved";
        }
        else
        {
             response.AccountNumber = "";
             response.Comment = "Credit rating is not sufficient";
        }                

        response.CustomerInformation = customer;
        response.LoanInformation = loan;
       
         return response;
    }
}				

需要添加几个 using 语句,提供使用的类的引用。把这些 using 语句放在代码的开头。

	using System.Web;
	using System.Web.Services;

Web.config

可以手工编辑 Web.config 文件,也可以使用 Windows Service Configuration Editor 编辑它。以后在为 Web 站点配置安全性时需要编辑它。

在 IIS 中配置 Web 服务

在 Visual Studio 中,选择 Build => Build Web Site 以检查代码错误。最常见的问题是代码顶部没有 using 语句。

通过设置 IIS 处理 WCF 服务:

  1. 选择 Windows Start => Control Panel。
  2. 双击 Administrative Tools。
  3. 双击 Internet Information Services (IIS) Manager。
  4. 如果 Default Web Site 下面没有出现您的 Web 服务,那么右键单击并选择 Add Application。
  5. 提供一个别名(比如 mywcf),找到 Web 服务位置(比如 C:\inetpub\wwwroot\mywcfservice)。
  6. 选择这个新服务,双击 IIS 部分中的 Handler Mappings。
  7. 在右边的 Actions 部分中,单击 Add Managed Handler。
  8. 在 Request Path 框中,输入 *.svc。
  9. 在 Type: 框中,输入
    System.ServiceModel.Activation.HttpHandler, System.ServiceModel,
    Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    

  10. 在 Name: 框中,输入 svc-Integrated。
  11. 单击 OK。
  12. 在右边的 Actions 部分中,单击 Add Script Map。
  13. 在 Request Path 框中,输入 *.svc。
  14. 在 Executable 框中,输入 C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll。
  15. 在 Name 框中,输入 svc-ISAPI-2.0。
  16. 单击 OK,如果弹出一个对话框的话,单击 Yes。
  17. 在 Handler Mappings 屏幕上,确认在列表中管理的处理器 (svc-Integrated) 出现在 aspnet_isapi (svc-ISAPI-2.0) 处理器前面。

上面的 IIS 配置将更新在 .NET 中开发的 Web 服务的 Web.config,以添加 *.svc 文件的条目。

测试 Web 站点

在 Visual Studio 中,打开 Web 服务的 Service.svc 文件,按 Ctrl-F5 打开一个浏览器以连接这个 Web 站点:


图 1. Web 站点测试
Web 站点测试

创建 WCF 客户机

  1. 选择 Windows Start => All Programs => Microsoft Visual Studio 2008 => Microsoft Visual Studio 2008。
  2. 选择 File => New => Project。
  3. 在 Project types 下面选择 Visual C#。
  4. 在 Templates 下面选择 Console Application。
  5. 设置客户机的名称,比如 myWCFClient,单击 OK。

在客户机中创建 Web 服务代理 API。

  1. 在右边的 Solution Explorer 面板上,右键单击 References 并选择 Add Service Reference。
  2. 在 Address 框中输入 Web 服务的名称,比如 http://myhostname/mywcfservice/Service.svc,单击 Go。
  3. 在 Services 下面,展开 Service 并选择 Iservice。操作应该会显示在右边面板中。
  4. 在 Namespace 中,指定适合客户机使用的名称空间,比如 mywcf.org,单击 OK。

客户机有两个需要开发或配置的主要组件:

  • Program.cs
  • app.config

Program.cs

在这个文件中,客户机设置要传递给 Web 服务的对象并处理它返回的对象。通过代理 API 调用访问 Web 服务,代理 API 调用的代码是在导入 Web 服务引用时生成的。这引用 app.config 文件中描述的绑定。例如:

myWCFClient.mywcf.org.ServiceClient mywcf =
                new myWCFClient.mywcf.org.ServiceClient("WSHttpBinding_IService", myURI);

下面的示例代码填充输入数据对象。然后,它通过代理调用 Web 服务,显示 Web 服务返回的值。

using ...

namespace MyWCFClient
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Count() < 1)
            {
                Console.WriteLine
         ("You must supply a target URL. 
For example: http://myhost/mywcfservice/Service.svc");
            }
            else
            {
                // Set the endpoint address for the service
                EndpointAddress myURI = new EndpointAddress(args[0]);

                myWCFClient.mywcf.org.ServiceClient mywcf = 
             new myWCFClient.mywcf.org.ServiceClient("WSHttpBinding_IService", myURI);

                string url = mywcf.Endpoint.Address.ToString();

                // Create some input data

                string firstName = "Gerrard";
                string lastName = "Bottles";
                string houseNumber = "222";
                string postCode = "PO12 9UW";
                DateTime dob = System.Convert.ToDateTime("22/02/82");
                int creditRating = 6;
                decimal amount = System.Convert.ToDecimal("1000.0");
                TimeSpan duration = new TimeSpan(System.Convert.ToInt32("3"));
                DateTime startDate = System.Convert.ToDateTime("03/10/2008");
                decimal interest = System.Convert.ToDecimal("5.4");

                // Populate the request data (Customer and Loan)
                myWCFClient.mywcf.org.LoanRequest request = 
                                                new myWCFClient.mywcf.org.LoanRequest();
                myWCFClient.mywcf.org.Customer customer = 
                                                   new myWCFClient.mywcf.org.Customer();
                customer.FirstName = firstName;
                customer.LastName = lastName;
                customer.HouseNumber = houseNumber;
                customer.PostCode = postCode;
                customer.DateOfBirth = dob;
                customer.CreditRating = creditRating;

                request.CustomerInformation = customer;

                myWCFClient.mywcf.org.Loan loan = new myWCFClient.mywcf.org.Loan();

                loan.Amount = amount;

                loan.Duration = duration;
                loan.StartDate = startDate;
                loan.InterestRate = interest;

                request.LoanInformation = loan;

                // Initiate the request to the service
                myWCFClient.mywcf.org.LoanApproval approval = 
                                                 mywcf.LoanApplicationRequest(request);

                Console.WriteLine("Approval state is " + approval.Approved.ToString());
                Console.WriteLine
  ("Approval credit rating is " + approval.CustomerInformation.CreditRating.ToString());
                Console.WriteLine("Comment is        " + approval.Comment);
                Console.WriteLine("Account Number is " + approval.AccountNumber);

                Console.WriteLine("URL is            " + url);

            }
        }
    }
}

需要添加几个 using 语句,提供使用的类的引用。一定要把 using 语句放在代码的开头: using System.ServiceModel;。保存 Program.cs 文件 (File => Save Program.cs)。

app.config

可以手工编辑 app.config 文件,也可以使用 Windows Service Configuration Editor 编辑它。以后在为客户机配置安全性时需要编辑它。

针对 Web 站点测试客户机

从 Visual Studio 菜单构建客户机:Build => Build myWCFClient。打开一个控制台窗口并运行客户机,这需要作为参数提供 Web 服务的地址。它应该会输出一个批准的结果,比如:

"C:\Users\myuser\Documents\Visual Studio 2008\Projects\
     myWCFClient\myWCFClient\bin\Debug\myWCFClient" 
        http://myvistahost/mywcfservice/Service.svc

Approval state is True
Approval credit rating is 6
Comment is        Request Approved
Account Number is 7106392
URL is           http://myvistahost/mywcfservice/Service.svc

在 Vista Web 服务主机上设置证书

在 Vista 机器上,使用命令行工具 makecert 为 Vista 服务器创建一个证书机构。

"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\makecert" -sk testRootCA 
    -sky signature -sr localmachine -n "CN=RootTrustedCA" -ss TRUST 
    -r RootTrustedCA.cer

确保 TRUST 密钥存储中只有这个证书机构:certutil -viewstore TRUST。如果不是这样,就使用 certutil -viewdelstore TRUST 删除其他证书机构。创建一个基于这个证书机构的证书,可以使用它交换密钥。

"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\makecert" -sk testServer 
    -ss MY -sky exchange -sr localmachine -n "CN=myvistahost" 
    -ic RootTrustedCA.cer -is TRUST myvistahost.cer -pe

其中的 myvistahost 是 Vista Web 服务主机的名称。

确认默认的 Vista NETWORK 用户可以访问证书:

"C:\Program Files (x86)\Microsoft WSE\v3.0\Samples\winhttpcertcfg" 
                               -g -c LOCAL_MACHINE\My -s myvistahost -a "NETWORK SERVICE"

"C:\Program Files (x86)\Microsoft WSE\v3.0\Samples\winhttpcertcfg" 
                               -l -c LOCAL_MACHINE\My -s myvistahost

使用 mmc 把 Vista 证书导入到 Vista 证书存储中:

  1. 选择 Windows Start。
  2. 在 Start Search 框中,输入 mmc 并按 Enter。
  3. 选择 File => Add\Remove Snap-in。
  4. 选择 Certificates 并单击 Add。
  5. 选择 Computer Account,选择 Next,确认选择了 Local computer,然后单击 Finish。
  6. 右键单击 Trusted Root Certification Authorities 并选择 All Tasks => Import。
  7. 按照向导进行设置,选择证书机构文件名,比如 RootTrustedCA.cer。
  8. 右键单击 Personal 并选择 All Tasks => Import。
  9. 按照向导进行设置,选择密钥交换证书文件名,比如 myvistahost.cer。

保护 WCF 服务和客户机

要配置 WCF 服务,让它参与与进行调用的(网关)客户机的 SSL 握手过程。要配置 WCF 客户机,让它在调用(网关)服务时使用 WS-Security。完成之后,WCF 客户机和服务还不能直接操作,因为客户机会产生服务不期望的 WS-Security 头部,而不产生服务需要的 SSL 加密的消息。WebSphere ESB 网关中介位于 .NET 客户机和 .NET 服务之间。WebSphere ESB 中介的导出将设置一个期望 WS-Security 的策略,而中介的导入被设置为生成 SSL 加密的消息。

Web.config SSL 配置

为了配置操作 WebSphere ESB 所需的 SSL,需要创建一个新的定制绑定并把它配置为使用 SOAP 1.1。可以手工编辑 Web.config 文件,也可以使用 Windows Service Configuration Editor 编辑它。

  1. 选择 Windows Start。
  2. 在 Start Search 框中输入 conf,从 Programs 菜单中选择 Service Configuration Editor。
  3. 选择 File => Open => Config File。
  4. 找到服务的 Web.config 文件(通常位于 C:\inetpub\wwwroot\mywcfservice)并单击 Open。
  5. 在 Configuration 面板中,右键单击 Bindings 并选择 New Binding Configuration。
  6. 在弹出的对话框中选择 customBinding 并单击 OK。
  7. 设置定制绑定的名称,比如 custom11。
  8. 在 Configuration 面板中展开新的定制绑定并选择 textMessageEncoding。
  9. 把 MessageVersion 设置为 Soap11。
  10. 在 Configuration 面板中选择新的定制绑定,在 Binding element extension position 表中选择 httpTransport,单击 Remove。
  11. 在 Configuration 面板中选择新的定制绑定,单击 Add,然后选择 httpsTransport 并单击 Add。下面是 Web.config 文件中的定制绑定小节:
    <customBinding>
        <binding name="custom11">
            <textMessageEncoding messageVersion="Soap11" />
            <httpsTransport />
        </binding>
    </customBinding>
    

  12. 在 Configuration 面板上,选择 Advanced => Service Behaviors => ServiceBehavior => serviceMetadata。
  13. 把 HttpGetEnabled 设置为 False,把 HttpsGetEnabled 设置为 True,以 https://myhostname:444/Securemywcfservice/Service.svc 的形式指定 HttpsGetUrl。在后面会看到如何使用 IIS 设置安全的 Web 站点。
  14. 选择 File => Save => File => Exit the Service Configuration Editor。
  15. 在 Visual Studio 中右边的 Solution Explorer 面板中,右键单击 Web.config 并选择 Open。
  16. 找到服务的 <service> 条目,比如 <service behaviorConfiguration="ServiceBehavior" name="Service">
  17. 用新的定制绑定(比如 custom11)的引用更新服务端点,把它由 wsHttpBinding 改为 customBinding。另外,把元数据交换绑定改为 mexHttpsBinding。为两个端点设置 https 风格的地址,创建一个 <host> 小节,其中包含 https 风格的 baseAddress。下面是一个示例:
    <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="https://myhostname:444/Securemywcfservice/Service.svc"
            binding="customBinding" bindingConfiguration="custom11" contract="IService">
            <identity>
                <dns value="localhost" />
            </identity>
        </endpoint>
        <endpoint address="https://myhostname:444/Securemywcfservice/Service.svc/mex"
                         binding="mexHttpsBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="https://myhostname:444/Securemywcfservice/Service.svc" />
          </baseAddresses>
        </host>
    </service>
    

  18. 在 <system.web> 小节下面,添加一个新的 <webServices> 小节,确保可以使用任何 SOAP 协议级别(默认设置是只使用 SOAP 1.2)。例如:
    <webServices>
        <protocols>
            <add name="AnyHttpSoap" />
        </protocols>
    </webServices>
    

  19. 保存 Web.config 文件。

创建使用 SSL 的安全 Web 站点

对于通过 SSL 使用的 Web 服务,它必须在 https 服务器上运行,还必须把 IIS 配置为支持 https 上的服务。

  1. 选择 Windows Start => Control Panel。
  2. 双击 Administrative Tools。
  3. 双击 Internet Information Services (IIS) Manager。
  4. 在 Connections 面板上,选择 Web Sites,右键单击并单击 Add Web Site。
  5. 设置 Web 站点名称。例如 Secure Web Site。
  6. 创建一个新目录(例如 C:\inetpub\wwwsroot)并设置这个目录的物理路径。
  7. 把 Binding Type 设置为 https。
  8. 把 Port 设置为 444。
  9. 把 SSL Certificate 设置为 Vista Web 服务主机证书并单击 OK。
  10. 在新创建的安全 Web 站点上,右键单击并选择 Add Application。
  11. 把 Alias 设置为 Securemywcfservice,确保它与 Web.Config 条目中设置的 https Web 站点值匹配。
  12. 设置到现有的不安全 Web 站点的物理路径。例如:C:\inetpub\wwwroot\mywcfservice。单击 OK。
  13. 现在,应该能够用安全地址通过浏览器访问安全 Web 站点,比如 https://myhostname:444/Securemywcf/Service.svc(可能必须接受证书)。

把客户机配置为使用 WS-Security

需要重新生成服务的客户机引用,反映对服务所做的修改。这个步骤相应地更新 app.config 文件。

  1. 在 Visual Studio 中打开客户机 (myWCFClient),在 Solution Explorer 中展开 Service References。
  2. 右键单击服务的引用 (mywcf.org) 并单击 Delete。
  3. 右键单击 Service References 并单击 Add Service Reference。
  4. 在 Address 框中输入安全 Web 服务的名称,比如 https://myhostname:444/Securemywcfservice/Service.svc。单击 Go(可能需要接受证书)。
  5. 在 Services 下面,展开 Service 并选择 Iservice。操作应该显示在右边的面板中。
  6. 在 Namespace 中,指定适合客户机使用的名称空间,比如 mywcf.org。单击 OK。

更新 Program.cs 以使用证书

在 Program.cs 中创建代理对象(上面示例中的 mywcf)之后添加以下代码:

mywcf.ClientCredentials.ServiceCertificate.SetDefaultCertificate( 
    System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,
        System.Security.Cryptography.X509Certificates.StoreName.My,
System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectDistinguishedName,
        "CN=wesbhost, O=mycompany, C=UK"
        );

其中的 wesbhost 是 WebSphere ESB 主机的证书别名(见下面的 “创建并交换密钥” 一节)。

更新 app.config 以使用 WS-Security

可以手工编辑 app.config 文件,也可以使用 Windows Service Configuration Editor 编辑它。对于这个示例,要配置 SSL 安全性:

  1. 选择 Windows Start。
  2. 在 Start Search 框中输入 conf,从 Programs 菜单中选择 Service Configuration Editor。
  3. 选择 File => Open => Config File。
  4. 找到服务的 app.config 文件(通常位于 C:\Users\myuser\Documents\Visual Studio 2008\Projects\myWCFClient\myWCFClient)并单击 Open。
  5. 导航到 Advanced => Endpoint Behaviors。
  6. 右键单击并选择 New Endpoint Behavior Configuration。
  7. 在 Name 框中指定一个名称,比如 Client-Cert-Behavior。
  8. 在 Behavior element extension position 面板中,单击 Add。
  9. 在弹出菜单中选择 clientCredentials 并单击 Add。
  10. 在 Configuration 面板中,展开新的行为并选择 clientCredentials => clientCertificate。
  11. 把 FindValue 设置为本地主机证书的名称 (myvistahost),把 StoreLocation 设置为 LocalMachine,保持 StoreName 为 My,把 X509FindType 设置为 FindBySubjectName。
  12. 展开 serviceCertificate 并选择 defaultCertificate。
  13. 把 FindValue 设置为 WebSphere ESB Web 服务主机证书的名称(这个证书的定义见下面的 “创建并交换密钥” 一节)。把 StoreLocation 设置为 LocalMachine,把 StoreName 设置为 TrustedPeople,把 X509FindType 设置为 FindBySubjectName。
  14. 在 Configuration 面板中,右键单击 Bindings 并选择 New Binding Configuration。
  15. 选择 customBinding 并单击 OK。
  16. 设置新定制绑定的名称 (Custom11)。
  17. 在 Configuration 面板中,选择新的定制绑定的 textMessageEncoding 项。
  18. 把 MessageVersion 设置为 Soap11。
  19. 在 Configuration 面板中,选择新的定制绑定。在 Binding element extension position 面板中,单击 Add。
  20. 选择 security 并单击 Add。
  21. 在 Configuration 面板中,选择新的定制绑定下面的 security 项。
  22. 把 AuthenticationMode 设置为 MutualCertificate,把 DefaultAlgorithmSuite 设置为 Basic128Rsa15,把 MessageSecurityVersion 设置为 WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10。

    根据服务或其平台的不同,MessageProtectionOrder 框需要不同的值。最初接受默认值 SignBeforeEncryptAndEncryptSignature,但是如果出现 “The primary signature must be encrypted” 这样的错误,就把它改为 SignBeforeEncrypt。

  23. 在 Configuration 面板中,选择现有的端点 CustomBinding_IService。
  24. 把 BehaviorConfiguration 设置为新的 Endpoint Behavior (Client-Cert-Behavior),把 Binding 设置为 customBinding,确认 BindingConfiguration 是定制绑定的名称 (Custom11)。
  25. 选择 File => Save 和 File => Close。
  26. 在 Visual Studio 中,选择 Project => myWCFClient Properties。
  27. 单击左边的 Security 选项卡。
  28. 选择 Enable Click Once Security Settings。
  29. 确认选择 This is a full trust application 并单击 Save。
  30. 构建客户机:选择 Build => Build myWCFClient。

更新 Program.cs 以使用新的绑定

在 Program.cs 中添加以下代码,创建代理对象(上面示例中的 mywcf):

myWCFClient.mywcf.org.ServiceClient mywcf = 
                 new myWCFClient.mywcf.org.ServiceClient("CustomBinding_IService", myURI);

保存文件并重新构建客户机:选择 Build => Build myWCFClient。

创建并交换密钥

用于 WS-Security 的证书(.NET 客户机 => WebSphere ESB Gateway)

在 WebSphere ESB 主机上,创建一个密钥和密钥存储,别名设置为主机名(这里所示的 wesbhost),例如:

keytool -genkey -v -alias wesbhost -validity 365 -keyalg "RSA" -keypass keypwd 
        -storepass storepwd -dname "CN=wesbhost,O=mycompany,C=UK" 
            -keystore /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks

从这个存储中导出一个证书,以后将把它导入 Vista 机器上的密钥存储。例如:

keytool -export -v -alias wesbhost -file wesbhost.cer -rfc -storepass storepwd 
	-keystore  /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks

在 “在 Vista Web 服务主机上设置证书” 一节中已经在 Vista 机器上创建了密钥。

把 WebSphere ESB 主机证书 (wesbhost.cer) 复制到 Vista 机器上,使用 mmc 把它导入 Trusted People Certificates 存储和 Personal Certificates 存储。

把在 “在 Vista Web 服务主机上设置证书” 一节中创建的 Vista 主机证书 (myvistahost.cer) 复制到 WebSphere ESB 主机上并把它导入密钥存储:

keytool -import -v -trustcacerts -alias myvistahost -file /home/myuser/myvistahost.cer 
	-storepass storepw -keystore  /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks
keytool -list -keystore  /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks

用于 SSL 的证书(WebSphere ESB Gateway => .NET 服务)

从 WebSphere ESB 服务器创建一个自签名证书,把它导入 Vista 服务器密钥存储:

  1. 在管理控制台中,选择 Security => SSL Certificate and key management => Key Store and Certificates。

    图 2. Key Store and Certificates
    Key Store and Certificates

  2. 选择 CellDefaultKeyStore。
  3. 选择 Personal certificates 并单击 Create a self-signed certificate。

    图 3. Personal certificates
    Personal certificates

  4. 输入完整的 WebSphere ESB 主机名作为 Alias 和 Common name(比如 wesbhost.company.com),在 Organization 框中输入相关文本。单击 OK 和 Save:

    图 4. Self-signed certificate
    Self-signed certificate

  5. 选择新证书并单击 Extract。
  6. 输入要创建的文件的完整路径(比如 /tmp/wesbhost.cer),确保数据类型是 Base64 编码的 ASCII 数据。单击 OK:

    图 5. Extract
    Extract

    这个文件将复制到 Vista 主机并导入它的密钥存储。

  7. 导航到 Security => SSL Certificate and key management => SSL Configurations。
  8. 选择 CellDefaultSSLSettings。
  9. 对于 Default server certificate alias 和 Default client certificate alias,选择刚才创建的证书。单击 OK:

    图 6. CellDefaultSSLSettings
    CellDefaultSSLSettings

  10. 导航到 Security => SSL Certificate and key management => Key Store and Certificates。
  11. 确认选中 CellDefaultKeyStore 和 CellDefaultTrustStore,单击 Exchange signers:

    图 7. Exchange signers
    Exchange signers

  12. 选择 WebSphere ESB 主机证书(比如 wesbhost.company.com)并单击 Add => OK => Save:

    图 8. Exchange Add
    Exchange Add

  13. 使用命令行停止部署管理器(当提示在可信存储中添加签署者时,回答 yes)。重新启动部署管理器。
  14. 把提取出的证书复制到 Vista 主机,使用 mmc 把它导入 Trusted Root Certification Authority 存储和 Personal Certificates 存储。

把 Vista 主机证书导入 WebSphere ESB 主机可信存储:

  1. 导航到 Security => SSL certificate and key management => Key stores and certificates。
  2. 选择 CellDefaultTrustStore。
  3. 选择 Signer certificates。
  4. 单击 Retrieve from port:

    图 9. Retrieve from port
    Retrieve from port

  5. 在 Host 框中输入 Vista 服务器主机名(比如 myvistahost)。输入 Vista 服务器的安全 Web 服务端口(比如 444)和合适的别名(比如 myvistahost_444)。单击 Retrieve signer information:

    图 10. Retrieve certificate
    Retrieve certificate

  6. 单击 OK 和 Save。

WebSphere ESB Service Gateway 设置

这个步骤创建一个简单的网关中介,它将把来自 .NET 客户机的输入消息路由到 .NET 服务:

  1. 启动 WID 6.2,进入 Business Integration 透视图。
  2. 创建一个 Gateway Library (File => New => Library)。
  3. 指定适当的库名,比如 GatewayLibrary。单击 Finish。
  4. 展开库并双击 Dependencies 项。
  5. 这会打开 Dependencies 编辑器,打开 Predefined Resources 部分。
  6. 选择 Service gateway interface and schema files 项,然后单击 Save 图标:

    图 11. Service gateway schema
    Service gateway schema

  7. 创建一个中介模块 (File => New => Mediation Module)。
  8. 指定适当的模块名 (GatewayModule),把 Target runtime environment 设置为 WebSphere ESB Server 6.2,单击 Next。
  9. 选择 GatewayLibrary 作为必需的库,单击 Finish。
  10. 在 Assembly Diagram 上,右键单击 Mediation 组件 (GatewayModule) 并选择 Add => Interface。
  11. 选择 ServiceGateway interface 并单击 OK:

    图 12. Service gateway interface
    Service gateway interface

  12. 右键单击 Mediation 组件并选择 Add => Reference。
  13. 选择 ServiceGateway 并单击 OK。
  14. 把一个 Import 拖到 Assembly Diagram 中 Mediation 组件的右边。
  15. 右键单击 Import 并从菜单中选择 Add Interface。
  16. 选择 ServiceGateway 并单击 OK。
  17. 右键单击 Import 并从菜单中选择 Generate Binding => Web Service Binding。
  18. 在 Transport Selection 对话框中,选择 SOAP1.1/HTTP 并单击 OK。
  19. 把 Mediation 组件的引用连接到 Import 的接口。
  20. 右键单击 Mediation 组件并选择 Generate Export => Web Service Binding。
  21. 在 Transport Selection 对话框中,选择 SOAP1.1/HTTP 并单击 OK。

    图 13. Assembly
    Assembly

  22. 双击 Mediation 组件以生成实现。
  23. 在 Mediation Flow Editor 中 Operation connections 下面,把 ServiceGateway 的 requestResponse 连接到 ServiceGatewayPartner 的 requestResponse。

    图 14. Operation connections
    Operation connections

  24. 在 Request flow 中,把一个 MessageElementSetter primitive 拖到画布中,把 Input primitive 连接到它的输入端,把它的输出端连接到 callout 节点。

    图 15. Request flow
    Request flow

  25. 选择 MessageElementSetter 的 Details 选项卡并单击 Add。
  26. 保持 Action 为 Set。
  27. 浏览 Target 并展开 header => SMOHeader => Target,双击 address 并单击 Finish。

    图 16. MES Address
    MES Address

  28. 在 Value 框中,输入网关发送消息的目标端点,比如 https://myvistahost:444/Securemywcfservice/Service.svc,然后单击 Finish。

    图 17. Endpoint
    Endpoint

  29. 再次单击 Add。
  30. 保持 Action 为 Set。
  31. 浏览 Target 并展开 header => SMOHeader。双击 Action 并单击 Finish。

    图 18. MES Action
    MES Action

  32. 在 Value 框中,输入服务 WSDL 中指定的操作调用路径,比如 http://tempuri.org/IService/LoanApplicationRequest。然后单击 Finish。

    图 19. Operation
    Operation

  33. 单击 Response 选项卡,把输入节点直接连接到响应节点:

    图 20. Response flow
    Response flow

  34. 保存 Flow 和 Assembly 图。
  35. 在 Projects 视图中,右键单击 Mediation 模块项目 (GatewayModule) 并从菜单中选择 Export。
  36. 在 Export 对话框中,展开 Business Integration,选择 Integration module 并单击 Next。
  37. 确认 Export usage 设置为 EAR files for server deployment 并选中了 GatewayModule 框。单击 Next。
  38. 浏览到适当的目标目录并单击 Finish。
  39. 把 EAR 文件部署到一个 WebSphere ESB 服务器。

WebSphere ESB 策略集配置

需要创建一个 WS-Security 策略并把它应用于 Gateway 服务。

创建定制的策略集

  1. 在左边面板上,选择 Services => Policy sets =>Application policy sets。
  2. 在右边面板上,选中 WSSecurity default 并单击页面顶部的 Copy。

    图 21. Application policy sets
    Application policy sets

  3. 在 Name 框中,输入 WSSecGW 并单击 OK。
  4. 选择刚创建的 WSSecGW 策略集。
  5. 选中 WS-Addressing,然后单击 Delete。
  6. 单击页面顶部的 Save。

    图 22. 删除 WS-Addressing
    删除 WS-Addressing

  7. 在左边面板上,选择 Services => Policy sets => Application policy sets。选择 WSSecGW,然后选择 WS-Security,接着选择 Main policy。

    图 23. Main policy
    Main policy

  8. 选择 Request message part protection。
  9. 在 Encrypted parts 下面,选择 app_encparts 并单击 Edit。

    图 24. Request message part
    Request message part

  10. 删除两个 XPath 语句:选择每个 XPath 表达式并单击 Remove Selected Elements。
  11. 单击 OK。

    图 25. Request message XPath
    Request message XPath

  12. 返回到 Main policy 对话框。
  13. 单击 Response message part protection。
  14. 在 Encrypted parts 下面,选择 app_encparts 并单击 Edit。
  15. 删除两个 XPath 语句:选择每个 XPath 表达式并单击 Remove Selected Elements。
  16. 单击 OK,然后单击 Save,返回到 Main policy 对话框。
  17. 确认选中 Include timestamp in security header。
  18. 单击 OK,然后单击 Save。

连接定制策略集和定制绑定

把策略集分配给服务:

  1. 在左边面板上,选择 Services => Service providers。
  2. 选择服务 ServiceGatewayExport1_ServiceGatewayHttpService,然后选中 ServiceGatewayExport1_ServiceGatewayHttpService 旁边的复选框。单击 Attach。
  3. 从下拉列表中选择 WSSecGW。

把定制绑定分配给服务:

  1. 在左边面板上,选择 Services => Service providers。
  2. 选择服务,然后选中服务,然后选择 Assign Binding => New。
  3. 指定 WS-GW-Binding 作为名称。
  4. 单击 Add,然后选择 WS-Security。
  5. 单击 Save。

    图 26. Assign Binding
    Assign Binding

配置服务请求签名消费者安全绑定

  1. 在左边面板上,选择 Services => Service providers。
  2. 选择服务 ServiceGatewayExport1_ServiceGatewayHttpService,然后选择 WS-GW-Binding,然后选择 WS-Security。
  3. 选择 Authentication and protection。

    图 27. Authentication and protection
    Authentication and protection

  4. 单击 AsymmetricBindingInitiatorSignatureToken0。
  5. 确认 JAAS login 是 wss.consume.x509。
  6. 单击 Apply 生成一个回调处理器绑定。

    图 28. AsymmetricBindingInitiatorSignatureToken0
    AsymmetricBindingInitiatorSignatureToken0

  7. 单击 Callback handler 链接。在 Callback handler 对话框中,确保选中 Trust any certificate。
  8. 在 Keystore 部分中,选择 Custom 作为名称,选择 Custom keystore configuration 链接。
  9. 在 Custom keystore configuration 对话框中,输入密钥存储的完整路径,比如 /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks。
  10. 对于 Type,选择 JKS。
  11. 对于 Password,输入密钥存储密码。
  12. 对于 Confirm password,输入密钥存储密码。
  13. 在 Key 部分中,在 Name 框中输入 Vista Web 服务主机的证书标签 CN=myvistahost,在 Alias 框中输入 Vista 主机名(证书别名),比如 myvistahost。
  14. 单击 OK 三次,然后单击 Save:

    图 29. Key Store
    Key Store

    AsymmetricBindingInitiatorSignatureToken0 现在显示为 Configured。

  15. 在 Request message signature and encryption protection 部分中,选择 request:app signparts。
  16. 在 Name 框中,输入 reqSign,然后单击 Apply。
  17. 在 Message part reference 部分中,选择 request:app_signparts,然后单击 Edit。
  18. 在 Transform algorithms 下面,单击 New。
  19. 在 URL 框中,输入 http://www.w3.org/2001/10/xml-exc-c14n#。
  20. 单击 OK 两次。

    图 30. Transform algorithms
    Transform algorithms

  21. 在 Signing key information 下面,单击 New。
  22. 在 Name 框中输入 reqSignKey。
  23. 确认在 Token generator or consumer name 框中选择了 AsymmetricBindingInitiatorSignatureToken0。单击 OK。

    图 31. Signing key
    Signing key

  24. 在 Signing key information 下面,选择 reqSignKey,然后单击 Add。
  25. 单击 OK,然后单击 Save。

    图 32. Request key
    Request key

    request:app_signparts 现在显示为 Configured。

配置服务请求加密消费者安全绑定

  1. 在左边面板上,选择 Services => Service providers。
  2. 选择服务,然后选择 WS-Server-Binding,然后选择 WS-Security。
  3. 选择 Authentication and protection。
  4. 选择 AsymmetricBindingRecipientEncryptionToken0。
  5. 确认 JAAS login 是 wss.consume.x509。
  6. 单击 Apply 生成一个回调处理器绑定。
  7. 选择 Callback handler 链接。
  8. 在 Certificates 下面,确保选中 Trust any certificate。
  9. 在 Keystore 部分中,选择 Custom 作为名称,然后选择 Custom keystore configuration 链接。
  10. 输入密钥存储的完整路径,比如 /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks。
  11. 对于 Type,选择 JKS。
  12. 对于 Password,输入密钥存储密码。
  13. 对于 Confirm password,输入密钥存储密码。
  14. 在 Key 部分中,在 Name 框中输入 WebSphere ESB 主机证书的标签(例如 CN=wesbhost)。
  15. 在 Alias 框中输入 WebSphere ESB 主机名(证书别名)wesbhost。
  16. 对于 keypass Password,输入密钥密码。
  17. 对于 Confirm keypass password,输入密钥密码。
  18. 单击 OK 三次,然后单击 Save。AsymmetricBindingRecipientEncryptionToken0 现在显示为 Configured。
  19. 在 Request message signature and encryption protection 下面,单击 request:app encparts。
  20. 在 Name 框中,输入 reqEnc,然后单击 Apply。
  21. 在 Key information 下面,单击 New。
  22. 输入 reqEncKey 作为名称。
  23. 确认对于 Token generator or consumer name 选择了 AsymmetricBindingRecipientEncryptionToken0。单击 OK。
  24. 在 Key information 下面,选择 reqEncKey,然后单击 Add。
  25. 单击 OK,然后单击 Save。request:app 现在显示为 Configured。

配置服务响应签名生成者安全绑定

  1. 在左边面板上,选择 Services => Service providers。
  2. 选择服务,然后选择 WS-Server-Binding,然后选择 WS-Security。
  3. 选择 Authentication and protection。
  4. 选择 AsymmetricBindingRecipientSignatureToken0。
  5. 确认 JAAS login 是 wss.generate.x509。
  6. 单击 Apply 生成一个回调处理器绑定。
  7. 选择 Callback handler 链接。
  8. 在 Keystore 部分中,选择 Custom 作为名称,然后选择 Custom keystore configuration 链接。
  9. 输入密钥存储的完整路径,比如 /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks。
  10. 对于 Type,选择 JKS。
  11. 对于 Password,输入密钥存储密码。
  12. 对于 Confirm password,输入密钥存储密码。
  13. 在 Key 部分中,在 Name 框中输入 WebSphere ESB 主机证书的标签(例如 CN=wesbhost)。
  14. 在 Alias 框中输入 WebSphere ESB 主机名(证书别名)wesbhost。
  15. 对于 Password,输入密钥密码。
  16. 对于 Confirm keypass password,输入密钥密码。
  17. 单击 OK 三次,然后单击 Save。AsymmetricBindingRecipientSignatureToken0 现在显示为 Configured。
  18. 在 Response message signature and encryption protection 下面,单击 response:app signparts。
  19. 在 Name 框中,输入 respSign。
  20. 在 Signing key information 下面,单击 New。
  21. 在 Name 框中,输入 respSignKey。
  22. 在 Type 下面,选择 X509 issuer name and issuer serial。
  23. 确认对于 Token generator or consumer name 选择了 AsymmetricBindingRecipientSignatureToken0。然后单击 OK,然后单击 Apply。
  24. 在 Message part reference 下面,选择 response:app_signparts 并单击 Edit。
  25. 在 Transform algorithms 下面,单击 New。
  26. 在 URL 框中,输入 http://www.w3.org/2001/10/xml-exc-c14n#。
  27. 单击 OK 两次。
  28. 在 Signing key information 下面,确保选择 respSignKey,然后单击 OK => Save。response:app 现在显示为 Configured。

配置服务响应加密生成者安全绑定

  1. 在左边面板上,选择 Services => Service providers => your Service。
  2. 选择 WS-Server-Binding,然后选择 WS-Security。
  3. 选择 Authentication and protection。
  4. 选择 AsymmetricBindingInitiatorEncryptionToken0。
  5. 确认 JAAS login 是 wss.generate.x509。
  6. 单击 Apply 生成一个回调处理器绑定。
  7. 选择 Callback handler 链接。
  8. 在 Keystore 部分中,选择 Custom 作为名称,然后选择 Custom keystore configuration 链接。
  9. 输入密钥存储的完整路径,比如 /opt/ibm/ESB/etc/ws-security/mySysKeys/wesbstore.jks。
  10. 对于 Type,选择 JKS。
  11. 对于 Password,输入密钥存储密码。
  12. 对于 Confirm password,输入密钥存储密码。
  13. 在 Key 部分中,在 Name 框中输入 Vista Web 服务主机证书的标签 CN=myvistahost。
  14. 在 Alias 框中输入 Vista 主机名(证书别名)myvistahost。
  15. 单击 OK 三次,然后单击 Save。AsymmetricBindingInitiatorEncryptionToken0 现在显示为 Configured。
  16. 在 Response message signature and encryption protection 下面,单击 response:app encparts。
  17. 在 Name 框中,输入 respEnc,然后单击 Apply。
  18. 在 Key information 下面,单击 New。
  19. 输入 respEncKey 作为名称。
  20. 在 Type 下面,选择 X509 issuer name and issuer serial。
  21. 确认对于 Token generator or consumer name 选择了 AsymmetricBindingInitiatorEncryptionToken0 并单击 OK。
  22. 确认选择 respEncKey,单击 OK,然后单击 Save。response:app 现在显示为 Configured。

通过 WebSphere ESB Gateway 测试 .NET 客户机/服务通信

为了从客户机调用服务,在 Vista 机器上打开一个命令控制台并使用客户机命令,作为参数提供 WebSphere ESB 服务网关的地址:

"C:\Users\myuser\Documents\Visual Studio 2008\Projects\
               myWCFClient\myWCFClient\bin\Debug\myWCFClient" 
               http://wesbhost:9080/GatewayModuleWeb/sca/ServiceGatewayExport1
Approval state is True
Approval credit rating is 6
Comment is Request Approved
Account Number is 413464
URL is http://wesbhost:9080/GatewayModuleWeb/sca/ServiceGatewayExport1

结束语

本文演示了如何在 .NET WCF 服务和 WebSphere ESB V6.2 Service Gateway 之间设置互操作性。另外,还讲解了如何使用 WebSphere ESB 策略集对 .NET 和 WebSphere ESB 之间的交互应用 Web 服务质量。



参考资料



关于作者

Andrew Howes 是位于英国的 IBM Hursley Software Lab 的 WebSphere ESB 系统验证测试团队的一位软件开发人员。




对本文的评价










回页首


IBM 公司保留在 developerWorks 网站上发表的内容的著作权。未经IBM公司或原始作者的书面明确许可,请勿转载。如果您希望转载,请通过 提交转载请求表单 联系我们的编辑团队。
    关于 IBM 隐私条约 联系 IBM 使用条款