WS-Security от soapUI до WCF - привязка и настройка

Мне нужно создать клиент WCF для вызова службы, которую я не могу контролировать, и нам был предоставлен только wsdl (со схемами). Веб-служба использует сертификат X.509 со спецификацией WS-Security версии 1.0.

Поставщик веб-службы поделился необработанным xml сообщения мыла, чтобы выделить заголовок ws-security. Используя soapUI, я смог создать точно такой же заголовок wsse-Security, как показано ниже:

<soapenv:Envelope xmlns:oas="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:oas1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xd="http://www.w3.org/2000/09/xmldsig#">
  <soapenv:Header>
    <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
      <ds:Signature Id="SIG-32" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
        <ds:SignedInfo>
          <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/>
          <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
          <ds:Reference URI="#id-31">
            <ds:Transforms>
              <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                <InclusiveNamespaces PrefixList="oas oas1 urn urn1 urn2 urn3 xd" xmlns="http://www.w3.org/2001/10/xml-exc-c14n#"/>
              </ds:Transform>
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
            <ds:DigestValue>ucSFZEOTHpe/IOlPVWtU+1xT4sM=</ds:DigestValue>
          </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>
          d4CKqie==
        </ds:SignatureValue>
        <ds:KeyInfo Id="KI-9A8D1F611E86CFB79E144316684667546">
          <wsse:SecurityTokenReference oas:Id="STR-9A8D1F611E86CFB79E144316684667547">
            <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"
                                ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3">5lAB5TaqeFwo23mRVm31LngBT1dQMf94mxeVkyKog==
            </wsse:KeyIdentifier>
          </wsse:SecurityTokenReference>
        </ds:KeyInfo>
      </ds:Signature>

      <oas:Timestamp oas:Id="TS-30">
        <oas:Created>2015-09-25T07:40:46.670Z</oas:Created>
        <oas:Expires>2015-09-26T11:27:26.670Z</oas:Expires>
      </oas:Timestamp>
    </wsse:Security>
  </soapenv:Header>

  <soapenv:Body oas:Id="id-31">
    ...
  </soapenv:Body>
</soapenv:Envelope>

В soapUI в разделе «Конфигурации WS-Security» я добавил Keystores (jks с моим личным сертификатом) и Truststores (jks с открытым корневым ключом CA). Наконец, я добавил «Исходящие конфигурации WS-Security» со следующими настройками.

С этим параметром WS-Security мыльное сообщение добавляетwsse:Security как показано выше.

Теперь мы создаем клиент WS на .NET с WCF и нуждаемся в помощи с настройками привязки и безопасности. Какие параметры привязки и конфигурации можно использовать для того же заголовка WS-Security, который требуется или показан выше?

Из WSDL я создал прокси на стороне клиента, используя WSCF.blue. Хотя я также мог бы использовать svcutil.exe или добавить ссылку на службу из VS.

Я попытался создать customBinding в коде, как показано ниже, но при проверке этого сообщенияwsse заголовок не такой как я хочу.

Например, он добавляетBinarySecurityToken вSecurity заголовок который не желателен.

ИлиKeyIdentifier являетсяX509SubjectKeyIdentifier вместоX509v3 например:<o:KeyIdentifier ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier" ...</o:KeyIdentifier>

Это также добавляет дополнительные несколькоReference подSignedInfo, и хотя он проходит проверку схемы, я не уверен, что дополнительныйReference делается.

internal static Binding GetCustomBinding()
{
    CustomBinding myBinding = new CustomBinding();

    AsymmetricSecurityBindingElement asBindingElement = new AsymmetricSecurityBindingElement();

    //Have tried these also
    //asBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12;
    //asBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
    //WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10

    asBindingElement.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
    asBindingElement.InitiatorTokenParameters = new System.ServiceModel.Security.Tokens.X509SecurityTokenParameters { InclusionMode = SecurityTokenInclusionMode.Never };

    asBindingElement.RecipientTokenParameters = new System.ServiceModel.Security.Tokens.X509SecurityTokenParameters 
    { 
        //X509ReferenceStyle = X509KeyIdentifierClauseType.SubjectKeyIdentifier,
        InclusionMode = SecurityTokenInclusionMode.Never
    };


    asBindingElement.MessageProtectionOrder = System.ServiceModel.Security.MessageProtectionOrder.SignBeforeEncrypt;
    //asBindingElement.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
    asBindingElement.SecurityHeaderLayout = SecurityHeaderLayout.LaxTimestampLast;
    asBindingElement.EnableUnsecuredResponse = true;
    asBindingElement.IncludeTimestamp = true;
    asBindingElement.SetKeyDerivation(false);
    asBindingElement.DefaultAlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic128Rsa15;

    asBindingElement.EndpointSupportingTokenParameters.Signed.Add(new X509SecurityTokenParameters());

    myBinding.Elements.Add(asBindingElement);

    myBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));
    //myBinding.Elements.Add(new MtomMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8));

    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
    httpsBindingElement.RequireClientCertificate = true;
    myBinding.Elements.Add(httpsBindingElement);

    return myBinding;
}

Кроме того, я использую это поведение для сертификата x509

<behaviors>
  <endpointBehaviors>
    <behavior name="MyBehavior">
      <clientCredentials>
        <clientCertificate findValue="xxx"
          storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />
        <serviceCertificate>
          <defaultCertificate findValue="xxx"
            storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />
          <authentication certificateValidationMode="None" revocationMode="NoCheck"
            trustedStoreLocation="LocalMachine" />
        </serviceCertificate>
      </clientCredentials>
    </behavior>
  </endpointBehaviors>
</behaviors>

Ответы на вопрос(1)

Ваш ответ на вопрос