Потребление услуги ws-security java от. NET WCF - PullRequest
0 голосов
/ 09 марта 2020

Я пытаюсь использовать этот WS "https://preproduccio.ejcat.justicia.gencat.cat/cee/TTA/TTAImport" из. NET, я не могу найти способ заставить его работать.

У меня уже есть рабочая версия в java, с использованием оси, но мне нужно перейти на. NET, и я не знаю, как мне go об этом.

Дело в том, что в java ( используя ось) я получаю запрос с этой структурой:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <soapenv:Header>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
            <wsse:BinarySecurityToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 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" wsu:Id="CertId-61394911">MIIH6zCCBdOgAwI...LwuaGzjUo</wsse:BinarySecurityToken>
            <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Signature-2">
                <ds:SignedInfo>
                    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                    <ds:Reference URI="#id-3">
                        <ds:Transforms>
                            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                        <ds:DigestValue>Ll/a2iv3aO9zg5PxuP62L1N3aNo=</ds:DigestValue>
                    </ds:Reference>
                    <ds:Reference URI="#Timestamp-1">
                        <ds:Transforms>
                            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                        <ds:DigestValue>vj0hStIyOttik2+CS1uFJhq6qGk=</ds:DigestValue>
                    </ds:Reference>
                    <ds:Reference URI="#CertId-613583B6441494911">
                        <ds:Transforms>
                            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                        <ds:DigestValue>v0BIV9LBHqga3WRDIJW91Rl0zjk=</ds:DigestValue>
                    </ds:Reference>
                </ds:SignedInfo>
                <ds:SignatureValue>loO68tBEAAYbC3YP1EZq+Rdv5...nV0RLzvb8x7Kw==</ds:SignatureValue>
                <ds:KeyInfo Id="KeyId-61358316B1B667F86F15724541498822">
                    <wsse:SecurityTokenReference xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-61358316B1B667F86F15724541499663">
                        <wsse:Reference URI="#CertId-61358316B1B667F86F15724541494911" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
                    </wsse:SecurityTokenReference>
                </ds:KeyInfo>
            </ds:Signature>
            <wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-1">
                <wsu:Created>2019-10-30T16:49:09.297Z</wsu:Created>
                <wsu:Expires>2019-10-30T16:54:09.297Z</wsu:Expires>
            </wsu:Timestamp>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-3">
        <consultaVersionsTME xmlns="http://www.openuri.org/">
            <ns1:ttaConsultaVersioTaulesMestres xmlns:ns1="http://xmlbeans.tta.justicia.gencat.cat">
                <ns1:dadesAplicacio>
                    <ns1:codiClient>XXXXXXXXX</ns1:codiClient>
                    <ns1:descClient>XXXXXXXXXXXXXXXXXXXX</ns1:descClient>
                    <ns1:CDA>LS0tLS1...VQkxJQyBLRVktLS0tLQ==</ns1:CDA>
                </ns1:dadesAplicacio>
            </ns1:ttaConsultaVersioTaulesMestres>
        </consultaVersionsTME>
    </soapenv:Body>
</soapenv:Envelope>

Но в. NET используя WCF вместо этого я получаю запрос с этой структурой:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <s:Header>
        <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo+Dl/UxaooVDuRCJMmSIwNAAAAAAfd11I2VSS02W50pL/gxFcLcmlnbUd01NkDPCbC8PqkQACQAA</VsDebuggerCausalityData>
        <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>2019-10-30T17:43:05.028Z</u:Created>
                <u:Expires>2019-10-30T17:48:05.028Z</u:Expires>
            </u:Timestamp>
            <o:BinarySecurityToken u:Id="uuid-9451dc94-ba71-4556-9ad8-7581a9572c40-1" 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">MIIH6zCCBdOgAwI...yqBfOFrNH8FBaV8ZFJRLwuaGzjUo</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>hrSyGrfDXj+bRpB2FZ7gFcYc8+Q=</DigestValue>
                    </Reference>
                </SignedInfo>
                <SignatureValue>TMPBkkTMi...HzY1i5OteHUEazrFgVW9SwuqCVn7MkIQBvw==</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-9451dc94-ba71-4556-9ad8-7581a9572c40-1"/>
                    </o:SecurityTokenReference>
                </KeyInfo>
            </Signature>
        </o:Security>
    </s:Header>
    <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <consultaVersionsTME xmlns="http://www.openuri.org/">
            <ttaConsultaVersioTaulesMestres xmlns="http://xmlbeans.tta.justicia.gencat.cat">
                <dadesAplicacio>
                    <codiClient>XXXXXXXXX</codiClient>
                    <descClient>XXXXXXXXXXXXXXXXXXXX</descClient>
                    <CDA>LS0tLS1CR...S0tRU5EIFBVQkxJQyBLRVktLS0tLQ==</CDA>
                </dadesAplicacio>
            </ttaConsultaVersioTaulesMestres>
        </consultaVersionsTME>
    </s:Body>
</s:Envelope>

, который является недействительным и WS отвечает, что раздел «Body» не имеет атрибута «Id», я пытался добавить его вручную с помощью SOAPUI, но затем он говорит, что сообщение не может быть правильно разложено или что-то подобное. Единственное, что я вижу, это разделы «Ссылка» из тела, и SecurityTokenReference отсутствуют в том, что генерирует WCF, но я не знаю, уместно ли это или как заставить его генерировать их.

Это это app.config из. NET:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="JwsServiceSoapBinding">
         <security authenticationMode="CertificateOverTransport"
                   includeTimestamp="true"
                   messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10">
          </security>
          <textMessageEncoding messageVersion="Soap11" />
          <transactionFlow />
          <httpsTransport/>     
        </binding>
      </customBinding>
    </bindings> 
    <client>
      <endpoint address="https://preproduccio.ejcat.justicia.gencat.cat/cee/TTA/TTAImport"
        binding="customBinding" bindingConfiguration="JwsServiceSoapBinding"
        contract="TTA.Jws" name="JwsServiceSoapBindingQSPort" />
    </client>
  </system.serviceModel>
</configuration>

Я перепробовал множество конфигураций, но мне не удалось использовать WS в. NET.

Это автоматическая c конфигурация привязки:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
  </startup>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="JwsServiceSoapBinding">
          <!--    WsdlImporter encontró aserciones de directiva no reconocidas en ServiceDescription 'http://www.openuri.org/':    -->
          <!--    <wsdl:binding name='JwsServiceSoapBinding'>    -->
          <!--        <wssp:Integrity xmlns:wssp="http://www.bea.com/wls90/security/policy">..</wssp:Integrity>    -->
          <!--        <wssp:MessageAge xmlns:wssp="http://www.bea.com/wls90/security/policy">..</wssp:MessageAge>    -->
          <textMessageEncoding messageVersion="Soap11" />
          <httpTransport />
        </binding>
      </customBinding>
    </bindings>

    <client>
      <endpoint address="http://preproduccio.ejcat.justicia.gencat.cat:80/cee/TTA/TTAImport"
        binding="customBinding" bindingConfiguration="JwsServiceSoapBinding"
        contract="TTA.Jws" name="JwsServiceSoapBindingQSPort" />
    </client>
  </system.serviceModel>
</configuration>

Есть идеи, как сделать эту работу?

ОБНОВЛЕНИЕ:

Итак, я сделал то, что предложил Авраам Цян, но оказалось, что Visual Studio 2015 неправильно генерирует привязку в app.config (возможно, это ошибка службы, хотя ...), поэтому мне пришлось изменить некоторые вещи, теперь это мой app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
  </startup>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="JwsServiceSoapBindingQSPort">
          <security defaultAlgorithmSuite="Default" 
                    authenticationMode="MutualCertificate"
                    requireDerivedKeys="false" 
                    securityHeaderLayout="Lax" 
                    includeTimestamp="true"
                    messageProtectionOrder="SignBeforeEncrypt" 
                    messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
                    requireSignatureConfirmation="false" 
                    enableUnsecuredResponse="true" 
                    allowInsecureTransport="true">            
                      <localClientSettings detectReplays="true" />
                      <localServiceSettings detectReplays="true" />            
          </security>
          <textMessageEncoding messageVersion="Soap11" />
          <httpsTransport/>
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="https://preproduccio.ejcat.justicia.gencat.cat/cee/TTA/TTAImport" binding="customBinding"
        bindingConfiguration="JwsServiceSoapBindingQSPort" contract="TTA.Jws"
        name="JwsServiceSoapBindingQSPort" />
    </client>
  </system.serviceModel> 
</configuration>

Мне пришлось изменить адрес на «https», удалить порт и изменить вместо «вместо». Теперь служба отвечает, но говорит:

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
   <env:Header/>
   <env:Body>
      <env:Fault xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <faultcode>wsse:InvalidSecurity</faultcode>
         <faultstring>Could not validate signature using any of the supported token types</faultstring>
         <detail>
            <java:string xmlns:java="java.io">weblogic.xml.crypto.wss.WSSecurityException: Could not validate signature using any of the supported token types</java:string>
         </detail>
      </env:Fault>
   </env:Body>
</env:Envelope>

Это мой запрос сейчас:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <s:Header>
      <VsDebuggerCausalityData xmlns="http://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink">uIDPo72vCydWNz5LsT1SUqDlThMAAAAA66I2Mc3lF0q8FjlnsBlDnnN96+MTv5RAs6MzleLgTC8ACQAA</VsDebuggerCausalityData>
      <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="uuid-ef984b26-f90c-4122-96f3-cc38f7398402-1">
            <u:Created>2020-03-19T13:32:05.693Z</u:Created>
            <u:Expires>2020-03-19T13:37:05.693Z</u:Expires>
         </u:Timestamp>
         <o:BinarySecurityToken u:Id="uuid-0b5c484b-72de-42c8-9687-955b0fa8e683-2" 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">MIIH6zCCBdOgAwIBAgIJAPMSJxLFf...H8FBaV8ZFJRLwuaGzjUo</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="#_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>ks8OJHwo/RExXvu9nYDCNPX9A4w=</DigestValue>
               </Reference>
               <Reference URI="#uuid-ef984b26-f90c-4122-96f3-cc38f7398402-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>PtSYgooa0nfTKwqZvvEK24yiEcw=</DigestValue>
               </Reference>
            </SignedInfo>
            <SignatureValue>RdQhmlFQEiU5mOQ3p4+Qg...cv3bYlB1/sdRXLzxZZdWosBmH25PJtzcgGwv9Iw==</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-0b5c484b-72de-42c8-9687-955b0fa8e683-2"/>
               </o:SecurityTokenReference>
            </KeyInfo>
         </Signature>
      </o:Security>
   </s:Header>
   <s:Body u:Id="_1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <consultaVersionsTME xmlns="http://www.openuri.org/">
         <ttaConsultaVersioTaulesMestres xmlns="http://xmlbeans.tta.justicia.gencat.cat">
            <dadesAplicacio>
               <codiClient>XXXX</codiClient>
               <descClient>XXXX</descClient>
               <CDA>LS0tLS1CRUdJ...BVQkxJQyBLRVktLS0tLQ==</CDA>
            </dadesAplicacio>
         </ttaConsultaVersioTaulesMestres>
      </consultaVersionsTME>
   </s:Body>
</s:Envelope>  

1 Ответ

0 голосов
/ 18 марта 2020

Теперь, когда базовый адрес на стороне клиента этой службы основан на HTTP, почему бы не попытаться настроить безопасность сообщений с помощью сертификата?

authenticationMode = "MutualCertificate"

Это требует от нас предоставления сертификата обслуживания. Кроме того, действия операции должны быть оформлены нижеприведенным утверждением.

ProtectionLevel=System.Net.Security.ProtectionLevel.Sign

Вот моя конфигурация клиента.

<system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="CustomBinding_ITestService">
          <security defaultAlgorithmSuite="Default" authenticationMode="MutualCertificate"
            requireDerivedKeys="false" securityHeaderLayout="Lax" includeTimestamp="true"
            messageProtectionOrder="SignBeforeEncrypt" messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
            requireSignatureConfirmation="false">
            <localClientSettings detectReplays="true" />
            <localServiceSettings detectReplays="true" />
          </security>
          <textMessageEncoding messageVersion="Soap11" />
          <httpTransport />
        </binding>
      </customBinding>
    </bindings>
    <client>
      <endpoint address="http://vabqia969vm:21011/" binding="customBinding"
        bindingConfiguration="CustomBinding_ITestService" contract="ServiceReference1.ITestService"
        name="CustomBinding_ITestService" />
    </client>
  </system.serviceModel>

Вызов на стороне клиента.

  ServiceReference1.TestServiceClient client = new TestServiceClient();
            client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindByThumbprint, "9ee8be61d875bd6e1108c98b590386d0a489a9ca");
            client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(StoreLocation.LocalMachine, StoreName.Root, X509FindType.FindByThumbprint, "5ba5022f527e32ac02548fc5afc558de1d314cb6");

            var result = client.GetResult();
            Console.WriteLine(result);

Формат запроса, захваченный скрипачом.
enter image description here
Для насмешек на стороне сервера (имя хоста: vabqia969vm) я создал следующую службу.

 class Program
    {

        /// <param name="args"></param>
        static void Main(string[] args)
        {

            using (ServiceHost sh = new ServiceHost(typeof(TestService)))
            {
                sh.Opened += delegate
                {
                    Console.WriteLine("service is ready");
                };

                sh.Closed += delegate
                {
                    Console.WriteLine("service is closed");
                };

                sh.Open();

            Console.ReadLine();
            sh.Close();
        }
    }
    }
    [ServiceContract(ProtectionLevel =System.Net.Security.ProtectionLevel.Sign)]
    public interface ITestService
    {
        [OperationContract]
        string GetResult();
    }

    [ServiceBehavior]
    public class TestService : ITestService
    {
        public string GetResult()
        {
            return DateTime.Now.ToLongTimeString();
        }
    }

Конфигурация на стороне сервера.

  <system.serviceModel>
<services>
  <service  name="ConsoleApp3.TestService">
    <endpoint address="" binding="customBinding" contract="ConsoleApp3.ITestService" bindingConfiguration="WsHttpSoap11" ></endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:21011"/>
      </baseAddresses>
    </host>
  </service>
</services>
<bindings>
  <customBinding>
    <binding name="WsHttpSoap11"  >
      <security allowSerializedSigningTokenOnReply="false"
                authenticationMode="MutualCertificate" 
                messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" 
                requireDerivedKeys="false" securityHeaderLayout="Lax" />
      <textMessageEncoding messageVersion="Soap11" />
      <httpTransport />
    </binding>
  </customBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior>
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="false"/>
      <serviceCredentials>
        <serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" findValue="5ba5022f527e32ac02548fc5afc558de1d314cb6"/>
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>

Не стесняйтесь, дайте мне знать, если есть что-то, с чем я могу помочь.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...