C# SOAP Служба: подписать элементы "wsu: Timestamp и wsa: To" в заголовке SOAP - PullRequest
1 голос
/ 06 мая 2020

Мне нужно использовать стороннюю службу в моем проекте c#. Я добавил подключенную службу в свою визуальную студию, чтобы получить ссылочные классы.

служба имеет особое требование c о подписании части запроса.

"Партнер будет использовать свой частный сертификат для создания блока подписи, подписывая определенные элементы c в блоке заголовка SOAP. Элементами, которые требуют подписи, являются wsu: Timestamp и wsa: To в заголовке. "

Я создал следующий код для инициализации EnrollmentServiceClient (класса подключенных служб) для вызова конечной точки

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;             
        }

Я вызываю указанный выше код в следующий фрагмент кода для подключения к службе

 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;
                }

Я могу сгенерировать запрос soap, но не могу подписать элементы wsu: Timestamp и wsa: To в заголовок. Я думаю, что это связано с SecurityBindingElement в методе InitializeClient выше.

Пожалуйста, помогите. Спасибо.

Обновление: Требуется SOAP формат заголовка

<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>

Я могу сгенерировать заголовок запроса SOAP, как требуется.

После добавления ссылки на службу в файл web.config была добавлена ​​следующая привязка

  <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>

Примечание : 1) на данный момент наш publi c ключи пока не обмениваются. Т.е. у меня нет служебного ключа для добавления, а наш сертификат publi c еще не добавлен в их доверенные root.

Обновление: я могу сгенерировать следующий SOAP запрос

<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">MIIG6zCCBdOgAwIBAgIJANJePKq6tlKqMA0GCSqGSIb3DQEBCwUAMIG0MQswCQYDVQQGEwJVUzEQMA4GA1UECBMHQXJpem9uYTETMBEGA1UEBxMKU2NvdHRzZGFsZTEaMBgGA1UEChMRR29EYWRkeS5jb20sIEluYy4xLTArBgNVBAsTJGh0dHA6Ly9jZXJ0cy5nb2RhZGR5LmNvbS9yZXBvc2l0b3J5LzEzMDEGA1UEAxMqR28gRGFkZHkgU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTIwMDMxOTIwMzgyOVoXDTIyMDIyMTIwMTYxM1owTTEhMB8GA1UECxMYRG9tYWluIENvbnRyb2wgVmFsaWRhdGVkMSgwJgYDVQQDEx90ZXN0LW9wdHVtLmVtcHlyZWFuYmVu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QQB1nkCBAIEggFtBIIBaQFnAHYApLkJkLQYWBSHuxOizGdwCjw1mAT5G9+443fNDsgN3BAAAAFw9ITTkAAABAMARzBFAiEA3lc7LRiAam3egya/sHOCNJuY4YjYpkrlRYWw1fsajXUCICRiKTqbSGHhoWRjJ6CS2b6ZXtArRdlW++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>
...