You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对WCF客户端SOAP消息的特定部分进行签名?

配置WCF CustomBinding实现SOAP消息特定部分签名

我需要和一个要求对消息特定部分签名的SOAP服务通信,在soapUI中可以完成这类配置(如下图),需要签名的内容包括WSA报头的From、To字段、时间戳以及消息体。我已经写了部分代码,但不知道在CustomBinding里该在哪里指定需要签名的特定部分,代码如下:

WSHttpBinding binding = new WSHttpBinding();
binding.Security = new WSHttpSecurity()
{
    Mode = SecurityMode.Transport,
    Transport = new HttpTransportSecurity()
    {
        ClientCredentialType = HttpClientCredentialType.Certificate,
    }
};

CustomBinding customBinding = new CustomBinding(binding);

UpdateBinding(customBinding);
private static void UpdateBinding(CustomBinding binding)
{
    var sec = SecurityBindingElement.CreateCertificateOverTransportBindingElement();
    sec.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic128Sha256;
    sec.IncludeTimestamp = true;

    binding.Elements.Insert(0, sec);
}

soapUI签名配置界面


要指定需要签名的特定部分,得在SecurityBindingElement上配置签名部件,具体步骤和修改后的代码如下:

CreateCertificateOverTransportBindingElement返回的是AsymmetricSecurityBindingElement类型,强转后就能访问签名相关配置属性。我们需要添加要签名的WSA报头,再明确指定签名消息体和时间戳:

private static void UpdateBinding(CustomBinding binding)
{
    // 强转为不对称安全绑定元素,才能配置签名部件
    var sec = (AsymmetricSecurityBindingElement)SecurityBindingElement.CreateCertificateOverTransportBindingElement();
    sec.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic128Sha256;
    sec.IncludeTimestamp = true;

    // 添加需要签名的WSA报头,注意匹配服务使用的WSA命名空间
    const string wsaNamespace = "http://www.w3.org/2005/08/addressing";
    sec.SignedHeaders.Add(new MessageHeaderSpecification("From", wsaNamespace));
    sec.SignedHeaders.Add(new MessageHeaderSpecification("To", wsaNamespace));

    // 明确指定要签名的部分:消息体、时间戳
    sec.SetSignatureParts(new SignedParts
    {
        Body = true,
        Timestamp = true
    });

    // 替换CustomBinding中原有的安全元素,避免重复添加导致异常
    var existingSecElement = binding.Elements.OfType<SecurityBindingElement>().FirstOrDefault();
    if (existingSecElement != null)
    {
        int index = binding.Elements.IndexOf(existingSecElement);
        binding.Elements[index] = sec;
    }
    else
    {
        binding.Elements.Insert(0, sec);
    }
}

关键注意点:

  • WSA报头的命名空间要和服务保持一致,如果服务用的是旧版WSA(比如http://schemas.xmlsoap.org/ws/2004/08/addressing),需对应修改
  • SetSignatureParts显式声明签名消息体和时间戳,确保这些部分不会被遗漏
  • 替换原有的安全元素而非插入新的,避免CustomBinding出现重复安全配置

内容的提问来源于stack exchange,提问作者zu1b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 03:35:08