Build SOAP Enveloped Request with. NET - PullRequest
0 голосов
/ 13 февраля 2020

Мне нужно создать запрос soap с подписью со следующей структурой:

<soapenv:Envelope
    xmlns:inf="http://www.trafico.es/servicios/vehiculos/comunicaciones/webservices/informeCompleto"
    xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsse:Security
            xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
            xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsse:BinarySecurityToken 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="X509-805CBAFED4FCA6EF3B158133158111621">{base 64 x509 certificate}</wsse:BinarySecurityToken>
            <ds:Signature Id="SIG-805CBAFED4FCA6EF3B158133158196124"
                xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:SignedInfo>
                    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                        <ec:InclusiveNamespaces PrefixList="inf soapenv"
                            xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </ds:CanonicalizationMethod>
                        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
                        <ds:Reference URI="#id-7cd5bd3a75ae401fb4b1cb504b223a034">
                            <ds:Transforms>
                                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
                                    <ec:InclusiveNamespaces PrefixList="inf"
                                        xmlns:ec="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>{digest value}</ds:DigestValue>
                            </ds:Reference>
                        </ds:SignedInfo>
                        <ds:SignatureValue>{sign}</ds:SignatureValue>
                        <ds:KeyInfo Id="KI-805CBAFED4FCA6EF3B158133158111622">
                            <wsse:SecurityTokenReference wsu:Id="STR-805CBAFED4FCA6EF3B158133158111623">
                                <wsse:Reference URI="#X509-805CBAFED4FCA6EF3B158133158111621" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
                            </wsse:SecurityTokenReference>
                        </ds:KeyInfo>
                    </ds:Signature>
                </wsse:Security>
            </soapenv:Header>
            <soapenv:Body wsu:Id="id-7cd5bd3a75ae401fb4b1cb504b223a034"
                xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
                <inf:obtenerInformeCompleto>
                    <solicitudInforme>
                        <doi>?</doi>
                        <matricula>?</matricula>
                        <codInforme>?</codInforme>
                        <motivoSolicitud>?</motivoSolicitud>
                        <numTasa>?</numTasa>
                    </solicitudInforme>
                </inf:obtenerInformeCompleto>
            </soapenv:Body>
        </soapenv:Envelope>

Я пытался построить запрос с WCF, потому что у меня есть файл .wsdl, но он не запускался, сервер, возвращенный к подписи, недействителен; (

Теперь я пытаюсь построить его с помощью класса xmldsig, но не получаю, сервер продолжает возвращать недопустимую подпись. Возможно ли получить ее с помощью этого? Класс xmldsig или WCF или. net c#?

Я вставляю свой код:

public XmlDocument createSoapRequest()
    {

        // Generate initial xml to sign
        XNamespace soapenv = CustomSignedXml.xmlSoapEnvelopeUrl;
        XNamespace service = "http://www.trafico.es/servicios/vehiculos/comunicaciones/webservices/informeCompleto";

        var vehicleReportXML = new XDocument(
            new XDeclaration("1.0", "utf-8", String.Empty),
                new XElement(soapenv + "Envelope",
                    new XAttribute(XNamespace.Xmlns + "inf", service),
                    new XAttribute(XNamespace.Xmlns + "soapenv", soapenv),
                    new XElement(soapenv + "Header"),
                    new XElement(soapenv + "Body",
                        new XElement(service + "obtenerInformeCompleto",
                            new XElement("solicitudInforme",
                                new XElement("doi", "?"),
                                new XElement("matricula", "?"),
                                new XElement("codInforme", "0"),
                                new XElement("motivoSolicitud", "0"),
                                new XElement("numTasa", "?")
                            )
                        )
                    )
                )
            );

        CustomXmlDsigDocument xmldsig = new CustomXmlDsigDocument();
        xmldsig.PreserveWhitespace = false;
        xmldsig.LoadXml(vehicleReportXML.ToString());

        XmlNamespaceManager nSpMgr = new XmlNamespaceManager(xmldsig.NameTable);
        nSpMgr.AddNamespace("inf", "http://www.trafico.es/servicios/vehiculos/comunicaciones/webservices/informeCompleto");
        nSpMgr.AddNamespace("soapenv", CustomSignedXml.xmlSoapEnvelopeUrl);
        nSpMgr.AddNamespace("wsu", CustomSignedXml.xmlOasisWSSSecurityUtilUrl);
        nSpMgr.AddNamespace("wsse", CustomSignedXml.xmlOasisWSSSecurityExtUrl);

        SignedXml sxml = new CustomSignedXml(xmldsig);

        sxml.SigningKey = this.Certificado.PrivateKey;


        string bodyID = "id-" + this.generateUid();
        string signatureID = "SIG-" + this.generateUid() + "2";
        string keyInfoID = "KI-" + this.generateUid() + "3";
        string securityTokenReferenceID = "STR-" + this.generateUid() + "4";
        string STRX509DataID = "X509-" + this.generateUid() + "5";


        // Find body and set body id
        XPathNavigator docNav = xmldsig.CreateNavigator();

        XPathNavigator bodyNav = docNav.SelectSingleNode("/soapenv:Envelope/soapenv:Body", nSpMgr);
        bodyNav.CreateAttribute("wsu", "Id", CustomSignedXml.xmlOasisWSSSecurityUtilUrl, bodyID);

        // Signature
        sxml.Signature.Id = signatureID;
        sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
        sxml.SignedInfo.SignatureMethod = SignedXml.XmlDsigRSASHA1Url;

        // Transformation Canonicalization Method
        XmlDsigExcC14NTransform canMethod = (XmlDsigExcC14NTransform)sxml.SignedInfo.CanonicalizationMethodObject;
        canMethod.InclusiveNamespacesPrefixList = "inf soapenv";

        // Reference to body ID
        Reference reference = new Reference();
        reference.Uri = "#"+ bodyID;   
        reference.DigestMethod = SignedXml.XmlDsigSHA1Url;
        XmlDsigExcC14NTransform c14n = new XmlDsigExcC14NTransform();
        c14n.InclusiveNamespacesPrefixList = "inf";  
        reference.AddTransform(c14n);
        sxml.AddReference(reference);

        // KeyInfo
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.Id = keyInfoID;
        // Optional
        //var certInfo = new KeyInfoX509Data();
        //certInfo.AddCertificate(this.Certificado);
        //keyInfo.AddClause(certInfo);
        //keyInfo.AddClause(new KeyInfoX509Data(this.Certificado));
        sxml.KeyInfo = keyInfo;

        // cross the fingers
        sxml.ComputeSignature(); 

        XmlElement xmlDigitalSignature = sxml.GetXml(); 

        // Complete xml request
        XPathNavigator headerNode = docNav.SelectSingleNode("soapenv:Envelope/soapenv:Header", nSpMgr);

        if (headerNode != null)
        {

            XmlElement secElement = xmldsig.CreateElement("wsse", "Security", CustomSignedXml.xmlOasisWSSSecurityExtUrl);
            secElement.SetAttribute("xmlns:wsu", CustomSignedXml.xmlOasisWSSSecurityUtilUrl);


            XPathNavigator secNav = secElement.CreateNavigator();
            headerNode.AppendChild(secNav);

            XPathNavigator secNode = headerNode.SelectSingleNode("wsse:Security", nSpMgr);

            if (secNode != null)
            {
                // Build node with x509 certificate data
                string token = Convert.ToBase64String(this.Certificado.RawData);
                XmlElement binSecTokElem = xmldsig.CreateElement("wsse:BinarySecurityToken", CustomSignedXml.xmlOasisWSSSecurityExtUrl);
                binSecTokElem.SetAttribute("EncodingType", CustomSignedXml.xmlOasisWSSSecurityExtUrl + "#Base64Binary");
                binSecTokElem.SetAttribute("ValueType", CustomSignedXml.xmlOasisWSSecurityTokenProfile);
                var attribute = xmldsig.CreateAttribute("wsu", "Id", CustomSignedXml.xmlOasisWSSSecurityUtilUrl);
                attribute.InnerText = STRX509DataID;
                binSecTokElem.SetAttributeNode(attribute);
                binSecTokElem.InnerText = token;
                var binSecTokNav = binSecTokElem.CreateNavigator();
                secNode.AppendChild(binSecTokNav);

                // Complete with node keyinfo
                XPathNavigator navSignature = xmlDigitalSignature.CreateNavigator();
                XmlElement keyInfoElement = xmldsig.CreateElement("ds:KeyInfo", STR_DS);
                keyInfoElement.SetAttribute("Id", keyInfoID);
                XmlElement securityTokenReferenceElement = xmldsig.CreateElement("wsse:SecurityTokenReference", CustomSignedXml.xmlOasisWSSSecurityExtUrl);
                var attribute2 = xmldsig.CreateAttribute("wsu", "Id", CustomSignedXml.xmlOasisWSSSecurityUtilUrl);
                attribute2.InnerText = securityTokenReferenceID;
                securityTokenReferenceElement.SetAttributeNode(attribute2);
                XmlElement referenceElement = xmldsig.CreateElement("wsse:Reference", CustomSignedXml.xmlOasisWSSSecurityExtUrl);
                referenceElement.SetAttribute("URI", "#"+STRX509DataID);
                referenceElement.SetAttribute("ValueType", CustomSignedXml.xmlOasisWSSecurityTokenProfile);
                securityTokenReferenceElement.AppendChild(referenceElement);
                keyInfoElement.AppendChild(securityTokenReferenceElement);
                XPathNavigator keyInfoElementNav = keyInfoElement.CreateNavigator();
                navSignature.AppendChild(keyInfoElementNav);
                secNode.AppendChild(navSignature);

           }
        }

        //string resultado = this.Consultar(xmldsig);

        return xmldsig;

    }

И добавляю пользовательские классы поддержки:

Спасибо .

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