C# SOAP Service : Sign “wsu:Timestamp and wsa:To ” elements in the SOAP header

感情迁移 提交于 2020-05-14 12:41:08

问题


I need to use a third-party service in my c# project. I have added the connected service in my visual studio to get the reference classes.

the service has a specific requirement about signing the part of the request.

"The partner will use their private certificate to create a signature block by signing specific elements in the SOAP header block. Elements that require signing are the wsu:Timestamp and wsa:To in the header."

I have created the following code to initialize an EnrollmentServiceClient (class of connected services) to call the endpoint

protected EnrollmentServiceClient InitializeClient(X509Certificate2 clientCertificate, X509Certificate2 serviceCertificate, string endpoint)
        {

            var security = SecurityBindingElement.CreateMutualCertificateBindingElement();// public certificates are shared between us and third party
            security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
            security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256Sha256;
            security.IncludeTimestamp = true;

            var encoding = new TextMessageEncodingBindingElement { MessageVersion = MessageVersion.Soap12WSAddressing10 };

            var transport = new HttpsTransportBindingElement { RequireClientCertificate = true };

            var binding = new CustomBinding();
            binding.Elements.Add(security);
            binding.Elements.Add(encoding);
            binding.Elements.Add(transport);

            var client = new EnrollmentServiceClient(binding, new EndpointAddress(new Uri(endpoint)));  
            client.ChannelFactory.Endpoint.Behaviors.Remove<ClientCredentials>();
            client.ChannelFactory.Endpoint.Behaviors.Add(new ClientCredentials());
            client.ClientCredentials.ClientCertificate.Certificate = clientCertificate;
            client.ClientCredentials.ServiceCertificate.DefaultCertificate = serviceCertificate;    
            return client;             
        }

I am calling the above code in the following snippet of code to connect to service

 var serviceClient = InitializeClient(CertFile, partnerCertFile, apiUrl);
                using (new OperationContextScope(serviceClient.InnerChannel))
                {
                    // Add a HTTP Header to an outgoing request
                    var requestMessage = new HttpRequestMessageProperty();
                    requestMessage.Headers["Content-Type"] = "application/soap+xml";
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
                    var activePlanYearResponse = serviceClient.GetActivePlanYear(activePlanYearRequest); //call specific endpoint,activePlanYearRequest are the request parameters
                    return activePlanYearResponse;
                }

I am able to generate the soap request, but I am not able to do the signing of the wsu:Timestamp and wsa:To elements in the header. I think it's related to SecurityBindingElement in the InitializeClient method above.

Please guide. Thanks.

Update: Required SOAP header format

<s:Header>
<a:Action s:mustUnderstand="1">http://services.lh1ondemand.com/hix/servicecontract/v1.0/DemographicService/GetConsumer</a:Action>
<a:MessageID>urn:uuid:6e4f5a20-65bf-4677-a6e5-7eeab5365d2b</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1" u:Id="_1">https://hixservice.lh1ondemand.com/v2_0/Demographic.svc</a:To>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="_0">
<u:Created>2015-03-20T18:39:31.162Z</u:Created>
<u:Expires>2015-03-20T18:44:31.162Z</u:Expires>
</u:Timestamp>
<o:BinarySecurityToken u:Id="uuid-84f8176f-e5e9-43b9-bad3-c808d20236e8-71" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">....</o:BinarySecurityToken>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#_0">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>Y4S33KKX+A+cPE9x780Qsir7HdI=</DigestValue>
</Reference>
<Reference URI="#_1">
<Transforms>
<Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>WOkaLqHmNbvB2v/YTNZQ3q0JN6k=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>.....</SignatureValue>
<KeyInfo>
<o:SecurityTokenReference>
<o:Reference ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" URI="#uuid-84f8176f-e5e9-43b9-bad3-c808d20236e8-71"/>
</o:SecurityTokenReference>
</KeyInfo>
</Signature>
</o:Security>
</s:Header>

I am able to generate the SOAP request header the same as required.

After adding the service reference, following binding was added in web.config file

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="{name2}">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" />
          </security>
        </binding>
      </basicHttpBinding>
      <wsHttpBinding>
        <binding name="{name1}">
          <security mode="TransportWithMessageCredential">
            <transport clientCredentialType="None" />
            <message clientCredentialType="Certificate" establishSecurityContext="false" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="{https url}"   binding="wsHttpBinding" bindingConfiguration="{configname}"
                contract="Service" name="{name1}" />
      <endpoint address="{https url}"
                binding="basicHttpBinding" bindingConfiguration="{configname2}"
                contract="Service" name="{name2}" />
    </client>
  </system.serviceModel>

Note: 1) as of now our public keys are not yet exchanged. I.e. I don't have the service key to add and our public certificate is not yet added to their trusted root.

Update: I am able to generate the following SOAP request

<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
    xmlns:a="http://www.w3.org/2005/08/addressing"
    xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <a:Action s:mustUnderstand="1">http://services.lh1ondemand.com/hix/servicecontract/v1.0/EnrollmentService/GetActivePlanYear</a:Action>
        <a:MessageID>urn:uuid:6f5a2b3d-5e0e-4729-9dc8-8ffc7f68a544</a:MessageID>
        <a:ReplyTo>
            <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
        </a:ReplyTo>
        <a:To s:mustUnderstand="1" u:Id="_1">https://hixservice.lh1ondemand.com/v2_0/Enrollment_V2_1.svc</a:To>
        <o:Security s:mustUnderstand="1"
            xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <u:Timestamp u:Id="_0">
                <u:Created>2020-05-12T09:40:10.439Z</u:Created>
                <u:Expires>2020-05-12T09:45:10.439Z</u:Expires>
            </u:Timestamp>
            <o:BinarySecurityToken u:Id="uuid-360122c6-3170-4086-aa2b-05eba2dc2b68-1" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">MIIG6zCCBdOgAwIBAgIJANJePKq6tlKqMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYDVQQGEwJVUzEQMA4GA1UECBMHQXJpem9uYTETMBEGA1UEBxMKU2NvdHRzZGFsZTEaMBgGA1UEChMRR29EYWRkeS5jb20sIEluYy4xLTArBgNVBAsTJGh0dHA6Ly9jZXJ0cy5nb2RhZGR5LmNvbS9yZXBvc2l0b3J5LzEzMDEGA1UEAxMqR28gRGFkZHkgU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTIwMDMxOTIwMzgyOVoXDTIyMDIyMTIwMTYxM1owTTEhMB8GA1UECxMYRG9tYWluIENvbnRyb2wgVmFsaWRhdGVkMSgwJgYDVQQDEx90ZXN0LW9wdHVtLmVtcHlyZWFuYmVuZWZpdHMuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoMPlFK7VUKETO7gmtBCLehW9vXH8uA4rE5XlV7HmHxFwTSJQ0fln044G2NEzr0FreseXNjq58pq/ntoiHRx35akh+RG4JN/L3itZIQ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S2b6ZXtArRdlW++tuTMRjU6q9AHYA7ku9t3XOYLrhQmkfq+GeZqMPfl+wctiDAMR7iXqo/csAAAFw9ITYagAABAMARzBFAiBt9ysFgNMKFych4LjWaizshMtvQv0xy/VwtN2Kn4XwLAIhANCT54MccgYgHHgIZUZPY95KwLo26uPkr5FpE7nyqNdGAHUAVhQGmi/XwuzT9eG9RLI+x0Z2ubyZEVzA75SYVdaJ0N0AAAFw9ITaqQAABAMARjBEAiAmYdfs2VnTIPary0I9E7boOt//WBlOQsIhbPGUe3BTjQIgPCyCF1pOEE9EWM6ol/bBGqOYwRx6ka7J0tVbZklIn2owDQYJKoZIhvcNAQELBQADggEBAJRJUvkbF4EHqgbQy/s0wA0jUuCD+6CdEsrzXL/KjRFoHXEgcusUOPzpDsjcA2jbEsii6MG05+80qn5ZoIC6RJ6ZKZmryVwXjk1i4Dy7B4BMCM8Y1ng4Kcj907o2qrFVaVEphwIKzvpX4fKUsD3qqcuU07MA+FV5kij2JoVwXpIb8K3kSAL1JdRCRq7BQWoyFU+Ix+T1NvnDDIxbP56jxWy4qVOFAlX9t7OD8ADQh1BTeQXscpQ7AhdixF0/8FjfNO9hcaumo9s8biB5vnX7yVTtAXmtXchWYV+859DlXh4W/Cvnu2PGbiWwP+xoy6O2/gE4cTV2TCfBBES6Hjd0V5E=</o:BinarySecurityToken>
            <Signature
                xmlns="http://www.w3.org/2000/09/xmldsig#">
                <SignedInfo>
                    <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                    <Reference URI="#_0">
                        <Transforms>
                            <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </Transforms>
                        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                        <DigestValue>BctJbbTtBqli8Z8Pwi0ENIjxz/ECKRBzn1oksr1TsAI=</DigestValue>
                    </Reference>
                    <Reference URI="#_1">
                        <Transforms>
                            <Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </Transforms>
                        <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                        <DigestValue>AnwxF4RTpgUd0NEBQu9QFuXw5ClD2N/T8zuSyhU8fMU=</DigestValue>
                    </Reference>
                </SignedInfo>
                <SignatureValue>NFz17hSnG5BXajAHKFhUiuGHdHF60iqWH+2XXHOAOu6IW3hhy/LzjqRiDFNANgGRO52EJgK+m43gqs6es0wos6PkzcEd/FN/Hv8vEVDjG1dt+jwo5RUZn6UZSi+ZUZdMW38a7y3P2N+2Ig7pNXOr4gkobxIRWB75v3KlmzJ1snjQ9fraHaKazi8u3bHQMLDhDmIhJLxvpxwGkInPzKE006WMQA0gIu0mGqZqrSasWJqNNeYcrejF580jozlsP5aoCYxxBMhgILcX87F5KN2l/WBw4YnHTx6jjhVQySaI3mh2MMNhYFScFfMTNw1yKtaImEVrZWgjOUEHBFG3rveqQw==</SignatureValue>
                <KeyInfo>
                    <o:SecurityTokenReference>
                        <o:Reference URI="#uuid-360122c6-3170-4086-aa2b-05eba2dc2b68-1"/>
                    </o:SecurityTokenReference>
                </KeyInfo>
            </Signature>
        </o:Security>
    </s:Header>

</s:Envelope>

来源:https://stackoverflow.com/questions/61632355/c-sharp-soap-service-sign-wsutimestamp-and-wsato-elements-in-the-soap-hea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!